This is the tutorial on the Fibonacci series in C with an example. Before that, you should have knowledge of the following topic in C.
What is Fibonacci Series?
Fibonacci series is the series of numbers where the next number is achieved by the addition of the previous two numbers. The initial addition of two numbers is 0 and 1.
For example: 0,1,1,2,3,5,8,13….etc.
We will learn two ways to display the Fibonacci series in C.
- using for loop
- using recursion
1. C Program to Generate Fibonacci Series using for loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #include <stdio.h> int main() { int i, n, term1 = 0, term2 = 1; int nextTerm = term1 + term2; printf("Enter the number of terms you want: "); scanf("%d", &n); printf("Fibonacci Series: %d, %d, ", term1, term2); for (i = 2; i < n; ++i) { printf("%d, ", nextTerm); term1 = term2; term2 = nextTerm; nextTerm = term1 + term2; } return 0; } |
Output:
Enter the number of terms you want: 10
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
2. Fibonacci series using Recursion in C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #include <stdio.h> void displayFibonacci(int); int main() { int num; printf("Enter the number of terms you want: "); scanf("%d", &num); printf("Fibonacci Series: %d %d ", 0, 1); displayFibonacci(num - 2); //since two numbers are already printed, hence n-2 return 0; } void displayFibonacci(int n) { static int term1 = 0, term2 = 1, nextTerm; if (n > 0) { nextTerm = term1 + term2; term1 = term2; term2 = nextTerm; printf("%d ", nextTerm); displayFibonacci(n - 1); } } |
Output:
Enter the number of terms you want: 10
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34