C Program to Generate Fibonacci Series
dev-suman-ch.blogspot.com
- Write a C program to Generate Fibonacci Series.
- Write a C program to Calculate Fibonacci Series.
Explanation
A series of numbers in which each number is the sum of the two preceding or previous numbers is called Fibonacci Series.
For example, Fibonacci series upto 7 numbers is 1, 1, 2, 3, 5, 8, 13.
In above example, first 2 numbers (1, 1) are printed directly as there are no preceding numbers. But after that, i.e the 3rd number (2) is the sum of 1st and 2nd number (1+1=2). Similarly to get 4th number, we add 2nd and 3rd number. (i.e., 1+2=3). You can use this pattern to find fibonacci series upto any number.
Mathematical expression to find Fibonacci number is :
Fn=Fn-1+Fn-2
i.e. To get nth position number, you should add (n-2) and (n-1) position number.
Program
#include <stdio.h>
int main() {
int i, n;
int a = 0, b = 1;
int sum = a + b;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: %d, %d, ", a, b);
for (i = 3; i <= n; i++) {
printf("%d, ", sum);
a = b;
b = sum;
sum = a + b;
}
return 0;
}
// Suman-Chakrabortty.web.app
// dev-suman-ch.blogspot.com
Output: Enter Fibonacci Range: 10 Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.
Algorithm
Step 1: Start
Step 2: Declare variable a, b, c, n, i
Step 3: Initialize variable a=0, b=1 and i=2
Step 4: Read n from user
Step 5: Print a and b
Step 6: Repeat until i<=n :
Step 6.1: c=a+b
Step 6.2: print c
Step 6.3: a=b, b=c
Step 6.4: i=i+1
Step 7: Stop
FlowChart
Genrerating Link.... 15 seconds.
Your Link is Ready.