C Program To Generate Fibonacci Series using For Loop


Lets write a C program to generate Fibonacci Series, using for loop.

Related Read:
Fibonacci Series using While loop: C Program

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

Video Tutorial: C Program To Generate Fibonacci Series using For Loop


[youtube https://www.youtube.com/watch?v=8VJVcwuYDPw]

YouTube Link: https://www.youtube.com/watch?v=8VJVcwuYDPw [Watch the Video In Full Screen.]


Source Code: C Program To Generate Fibonacci Series using For Loop

#include<stdio.h>

int main()
{
    int n1 = 0, n2 = 1, n3, count, num;

    printf("Enter the number of terms to be printed\n");
    scanf("%d", &num);

    printf("\n%d\n%d\n", n1, n2);

    for(count = 3; count <= num; count++)
    {
        n3 = n1 + n2;
        printf("%d\n", n3);

        n1 = n2;
        n2 = n3;
    }

    return 0;
}

Output:
Enter the number of terms to be printed
10

0
1
1
2
3
5
8
13
21
34

Logic To Generate Fibonacci Series using For Loop

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 For loop logic. Since we’ve already printed two Fibonacci numbers, we assign 3 to loop control variable count and iterate through the for loop till count is less than or equal to the user entered number.

Inside For loop
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.

For loop keeps repeating above steps until the count is less than or equal to the user entered number. If the user entered limit/count is 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

Leave a Reply

Your email address will not be published. Required fields are marked *