In this tutorial, we will learn two following ways to display Fibonacci series in C programming language:

1) Using For loop

2) Using recursion

### Fibonacci Series in C using loop

A simple for loop to display the series. Program prompts user for the number of terms and displays the series having the same number of terms.

#include<stdio.h> int main() { int count, first_term = 0, second_term = 1, next_term, i; //Ask user to input number of terms printf("Enter the number of terms:\n"); scanf("%d",&count); printf("First %d terms of Fibonacci series:\n",count); for ( i = 0 ; i < count ; i++ ) { if ( i <= 1 ) next_term = i; else { next_term = first_term + second_term; first_term = second_term; second_term = next_term; } printf("%d\n",next_term); } return 0; }

Output:

Enter the number of terms: 8 First 8 terms of Fibonacci series: 0 1 1 2 3 5 8 13

### Program to display Fibonacci series using recursion

Here we are using a user defined function fibonacci_series() that calls itself recursively, in order to display series for the entered number of terms.

#include<stdio.h> int fibonacci_series(int); int main() { int count, c = 0, i; printf("Enter number of terms:"); scanf("%d",&count); printf("\nFibonacci series:\n"); for ( i = 1 ; i <= count ; i++ ) { printf("%d\n", fibonacci_series(c)); c++; } return 0; } int fibonacci_series(int num) { if ( num == 0 ) return 0; else if ( num == 1 ) return 1; else return ( fibonacci_series(num-1) + fibonacci_series(num-2) ); }

Output:

Enter number of terms: 6 Fibonacci series: 0 1 1 2 3 5

## Leave a Reply