Today lets see how to generate Fibonacci Series using while loop in C programming.
First Thing First: What Is Fibonacci Series ?
Fibonacci Series is a series of numbers where the first two Fibonacci numbers are 0 and 1, and each subsequent number is the sum of the previous two. Its recurrence relation is given by Fn = Fn-1 + Fn-2.
Below are a series of Fibonacci numbers(10 numbers):
0
1
1
2
3
5
8
13
21
34
How Its Formed:
0 <– First Number (n1)
1 <– Second Number (n2)
1 <– = 1 + 0
2 <– = 1 + 1
3 <– = 2 + 1
5 <– = 3 + 2
8 <– = 5 + 3
13 <– = 8 + 5
21 <– = 13 + 8
34 <– = 21 + 13
Generate Fibonacci Series using While loop: C Program
[youtube https://www.youtube.com/watch?v=LhM2pvYwMDs]
Source Code: Fibonacci Series using While loop: C Program
#include < stdio.h > int main() { int n1 = 0, n2 = 1, n3, count; printf("Enter the limit\n"); scanf("%d", &count); printf("\n%d\n%d\n", n1, n2); count = count - 2; while(count) { n3 = n1 + n2; printf("%d\n", n3); n1 = n2; n2 = n3; count = count - 1; } return 0; }
Output:
Enter the limit
10
0
1
1
2
3
5
8
13
21
34
Logic to Generate Fibonacci Series in C Programming Language
We know that the first 2 digits in fibonacci series are 0 and 1. So we directly initialize n1 and n2 to 0 and 1 respectively and print that out before getting into while loop logic. Since we’ve already printed two fibonacci numbers we decrement the value of variable count by 2.
Inside while loop
We already know that C program treat any non-zero number as true and zero as false. So once the value of variable count is zero, the execution of while loop stops. So the condition while(count) is equal to writing while(count == 0). We decrement the value of count by 1 each time the loop executes. So once count is 0 the loop execution stops.
As per definition of Fibonacci series: “..each subsequent number is the sum of the previous two.” So we add n1 and n2 and assign the result to n3 and display the value of n3 to the console.
Next, we step forward to get next Fibonacci number in the series, so we step forward by assigning n2 value to n1 and n3 value to n2.
While loop keeps repeating above steps until the count is zero. If the user entered limit/count as 10, then the loop executes 8 times(as we already printed the first two numbers in the fibonacci series, that is, 0 and 1).
For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List
For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert