What is the Fibonacci sequence?
In the Fibonacci series, each number is the sum of the two previous numbers. The first two numbers in the Fibonacci series are 0 and 1.
The sequence Fn of Fibonacci numbers is defined by the recurrence relation:
Fn = Fn-1 + Fn-2 ( where, n > 1) with seed values F0 = 0 and F1 = 1.
The beginning of the sequence is thus:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ……..
Algorithm to generate Fibonacci sequence using C program:
- Get the Fibonacci series limit from the user, say n.
- Assign “preValue1” = 0, “preValue2” = 1.
- Assign the addition of”preValue1 and preValue2” to “next”.
next = preValue1 + preValue2 - Swap “preValue2” to “preValue1” and “next ” to “preValue2”.
- Repeat steps 3 and 4 till n.
See the C program to generate the Fibonacci sequence based on the number of terms entered by the user.
#include <stdio.h> int main() { int num, i = 0, next, preValue1 = 0, preValue2 = 1; printf("Enter no. of terms: "); scanf("%d",&num); if(num < 0) { printf("Enter valid number\n"); } else { while(i < num) { if(i <= 1) { next = i; } else { next = preValue1 + preValue2; preValue1 = preValue2; preValue2 = next; } printf("%d \t", next); i++; } } return 0; }
Output:
Enter no. of terms: 5
0 1 1 2 3