Fibonacci Series in C using For Loop

Before going to the program first let us understand what is a Fibonacci Series?

Fibonacci Series:

                  Fibonacci series is nothing but a Series of Numbers which are found by adding the two preceding(previous) Numbers.

For Example,

0,1,1,2,3,5,8,13,21 is a Fibonacci Series of length 9.

For more understanding you can check out the following link:

https://www.mathsisfun.com/numbers/fibonacci-sequence.html

Program code to Display Fibonacci Series in C:

#include<stdio.h>
#include<conio.h>
void main()
{
    int n,i,f,f1=0,f2=1;
    clrscr();
    
    printf("  Enter The Number:");
    scanf("%d",&n);
    
    printf("  The Fibonacci Series is:");
    printf("  \n %d\n %d",f1,f2);
    
    for(i=2;i<n;i++)
    {
        f=f1+f2;
        f1=f2;
        f2=f;
        printf("  \n %d",f);
    }
    
    getch();
}

Related: Fibonacci Series in C++ using For Loop

Working:

  • First the computer reads the value of number of terms for the Fibonacci series from the user.
  • Then using for loop the two preceding(previous) numbers are added and printed.
  • The loop continues till the value of number of terms.

Step by Step working of the above Program Code:

Let us assume that the Number of Terms entered by the user is 5.

  1. It assigns the value of n=5 and prints the first two numbers “f1” and “f2” (ie. 0 and 1) on the output screen.
  2. Then it assigns the value of i=2 in the initialization part of the for loop.
  3. Then the loop continues till the condition of the for loop is true.

3.1.    i<n      (2<5), for loop condition is true

f=f1+f2         (f=0+1)         So f=1

f1=f2             (f1=1)            So f1=1

f2=f               (f2=1)           So f2=1

print the value of “f” (ie. 1)

i++                (i=i+1)         So i=3

3.2.    i<n      (3<5), for loop condition is true

f=f1+f2         (f=1+1)         So f=2

f1=f2             (f1=1)            So f1=1

f2=f               (f2=2)           So f2=2

print the value of “f” (ie. 2)

i++                (i=i+1)         So i=4

3.3.    i<n      (4<5), for loop condition is true

f=f1+f2         (f=1+2)         So f=3

f1=f2             (f1=2)            So f1=2

f2=f               (f2=3)           So f2=3

print the value of “f” (ie. 3)

i++                (i=i+1)         So i=5

3.4.    i<n      (5<5), for loop condition is false

comes out of the for loop.

  1. Thus the program execution is completed.

Output:

fibonacci series
fibonacci series

TO DOWNLOAD THE PROGRAM CODE :CLICK HERE

 

Leave a Reply

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