Skip to main content

Code to write Fibonacci series for number of elements as per user input.

Fibonacci series means a series of numbers in which each number is the sum of the two preceding numbers. Example is 1, 1, 2, 3, 5, 8

Below is C program code to print Fibonacci series as per user input.

for e.g if user input 20 then program will print 20 elements in Fibonacci series.

//Program Name: Print fibonacci series using for loop upto n term
// for e.g 1, 1, 2, 3, 5, 8

#include <stdio.h>

void main()
{
    int s1=0,s2=1; //initializing first two numbers 
    int nextNum=0,numCnt=0,i;

    printf("\n\n\tPlease enter how many numbers need to print in Fibonacci series.\t");
    scanf("%d",&numCnt);
    //here assuming user will enter value more than 1 
    //printing first two numbers
    printf("\n\tBelow are %d numbers in Fibonacci Series  ",numCnt);
    printf("\n\n\t%d %d",s1,s2);
     for(i=2;i<numCnt;i++)
    {    
        nextNum=s1+s2;
        printf(" %d",nextNum); 
        s1=s2;    
        s2=nextNum; 
       
    }  
}

Output

        Please enter how many numbers need to print in Fibonacci series.       20

        Below are 20 numbers in Fibonacci Series  

        0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181

If you want to print Fibonacci series up to particular number then refer this link