In this article, you will learn to print the Fibonacci sequence of first n term.
Fibonacci Series generates subsequent number by adding two previous numbers.
The first two terms of the Fibonacci sequence are 0 followed by 1.
The Fibonacci sequence:
0, 1, 1, 2, 3, 5, 8, 13, 21 ...
In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation
Fn = F(n-1) + F(n-2)
where,
F0 = 0 and F1 = 1
Algorithm :
Algorithm of this program is very easy −
- Take integer variable A, B, C
- Set A = 0, B = 0
- DISPLAY A, B
- C = A + B
- DISPLAY C
- Set A = B, B = C
- REPEAT from 4 – 6, for n times
Implementation :
1. Using loop :
// C Program for Fibonacci numbers #include <stdio.h> // driver code int main() { // intial terms int a = 0, b = 1; // print intial terms printf("%d %d ",a, b); // for next 10 term int n = 10; int i; for(i = 1; i <= n-2; i++) { // to store result int c; c = a + b; //print result printf("%d ", c); // new previous two terms a = b; b = c; } // successful completion return 0; }
Output :
0 1 1 2 3 5 8 13 21 34
2. Using Recursion :
// C Program for Fibonacci numbers #include<stdio.h> int fibonacci_series(int); // driver code int main() { // take input, i.e., number of terms int terms = 10; int c = 0, i ; for ( i = 1 ; i <= terms ; i++ ) { // call fib series function printf("%d ", fibonacci_series(c)); c++; } return 0; } // fib series function int fibonacci_series(int num) { // for first intial term if ( num == 0 ) return 0; // for second intial term else if ( num == 1 ) return 1; else // for more than two terms return ( fibonacci_series(num-1) + fibonacci_series(num-2) ); }
Output :
0 1 1 2 3 5 8 13 21 34
3. Using Dynamic Programming :
//Fibonacci Series using Dynamic Programming #include<stdio.h> // fib function int fib(int n) { // Declare an array to store Fibonacci numbers int f[n+2]; int i; // for intial two terms f[0] = 0; f[1] = 1; // print these intial terms printf("%d ", f[0]); printf("%d ", f[1]); // for more two terms for (i = 2; i <= n; i++) { // ass previous two numbers and store f[i] = f[i-1] + f[i-2]; printf("%d ", f[i]); } return f[n]; } int main () { // take input, i.e., total number of terms int n = 10; // call fib function fib(n); // successful completion return 0; }
Output :
0 1 1 2 3 5 8 13 21 34 55
Please write comments if you find anything incorrect. A gentle request to share this topic on your social media profile.