Skip to main content

How to write simple C Program for Fibonacci series using for loop

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 or up to n number.

for e.g if user input 200 then program will print Fibonacci series till 200 meaning sum which is less than or equal to 200.

//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,SumUpto=0;

    printf("\n\n\tPlease enter number up to which print Fibonacci series is required \t");
    scanf("%d",&SumUpto);
    //here assuming user will enter value more than 1 
    //printing first two numbers
    printf("\n\tfibbonacci Series up to %d is ",SumUpto);
    printf("\n\n\t%d  %d",s1,s2);
     for(nextNum=2;nextNum<=SumUpto;)
    {    
 
        s1=s2;    
        s2=nextNum; 
        printf(" %d",nextNum); 
        nextNum=s1+s2;
    }  
}

Output


        Please enter number up to which print Fibonacci series is required      200

        Fibonacci Series up to 200 is 

        0  1 2 3 5 8 13 21 34 55 89 144

Another method to find the Fibonacci numbers is by using the golden ratio (1.618034).

Here is a method to find the Fibonacci series using the golden ratio method.

Just by multiplying the previous Fibonacci Number by the golden ratio(1.618034), we get the approximated Fibonacci number. For example, 2 × 1.618034… = 3.236068. This gives the next Fibonacci number 2 after 3.

C code for Fibonacci series using the golden ratio.

// Fibbonaci series using golden ratio.
#include <stdio.h>
#include <math.h>
int main() {
    // Write C code here
    float result=1.0;
    //result=1.0;
    printf("\n0\n1\n1");
    for(int i=1;i<15;i++)
    {
        result = lround( result * (1.618034));
        printf("\n%d",lround(result));
    }
}

Output

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