Fibonacci series in C using while loop

(Last Updated On: 11/12/2023)

The Fibonacci series, a key mathematical sequence, holds profound importance in both mathematics and computer science. This blog explores its significance while delving into the fundamentals of the C programming language. Understanding loops, particularly the while loop, becomes pivotal in unraveling the magic behind the generation of the Fibonacci series in C.

// Fibonacci series in C using while loop
#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;
}

Know the Fibonacci Series in Python Using For Loop here!

Explanation of the code:

This C program generates a Fibonacci series using a while loop. It begins by initializing the first two numbers, n1 and n2, as 0 and 1, respectively. 

The user is prompted to input the limit of the series, stored in the ‘count’ variable. 

The initial values are then printed. Using a while loop, the program calculates the next Fibonacci number (n3) by adding the previous two (n1 and n2). 

This process continues until the desired count is reached, with each new Fibonacci number being printed. 

The loop iterates, updating variables to progress the series, and the program concludes after generating the specified Fibonacci sequence.

Output:

Explore the fascinating world of For Loop in C Check out!

Enter the limit 8
0
1
1
2
3
5
8
13

In conclusion, the Fibonacci series, a mathematical marvel, finds applications across diverse fields. Its beauty lies in its recurrence and influence on nature, art, and algorithms. This exploration highlights the while loop’s pivotal role, showcasing its importance in unraveling the mesmerizing patterns of the Fibonacci sequence.

Newtum Online Compiler is a valuable resource offering quality education and support for programming and tech enthusiasts, facilitating effective learning.

About The Author