C program to print Fibonacci series


Consider you want to print the Fibonacci series upto terms given by user.

Fibonacci series starts from 0 and 1 and then continued by the addition of the preceding two numbers. For example : 0, 1, 1, 2, 3, 5, 8, 13,....

#include <stdio.h>
int main()
{
  int first = 0;
  int second = 1;
  int i, next, terms;
  
  printf("Enter how many terms:");
  scanf("%d", &terms);
  
  if (terms <= 0){
     printf("Invalid input");
  } else if (terms == 1){
      printf("\nFibonacci series up to %d terms:",terms);
      printf("%d",first);
    } else {
        printf("\nFibonacci series up to %d terms:",terms);
        for ( i=0;i<terms;i++){
          printf("%d\n",first);
          next = first + second;
          first = second;
          second = next;
        }
      }
}

Try yourself here by providing input in the stdin section.

In the above program,

  • Initializing first to 0 and second to 1.
  • we are checking if the input given by user is valid.
  • If the user requested for only 1 term then print 0.
  • Otherwise we are using for loop based on the condition, count(i) should be less than terms given by user.
  • Logic:
     next = first + second
     first = second
     second = next

Results

Enter how many terms: 10
Fibonacci series up to 10 terms:
0
1
1
2
3
5
8
13
21
34