OverIQ.com

C Program to generate Fibonacci sequence

Last updated on September 23, 2020


What is Fibonacci sequence? #

Fibonacci sequence is series in which each successive number is the sum of the previous two numbers. For example:

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

The following is a C program to generate Fibonacci sequence based on the number of terms entered by the user.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/*******************************************************
 * Program to generate Fibonacci sequence
********************************************************/

#include<stdio.h> // include stdio.h

int main()
{
    long int x = 0, y = 1, z;       
    int terms, i = 1;

    printf("Enter no. of terms: ");
    scanf("%d", &terms);   // to suppress the compiler warning in Linux replace %d with %zu

    printf("%d ", y);

    while(i <= terms - 1)
    {
        z = x + y;
        x = y;
        y = z;
        printf("%d ", z);  // to suppress the compiler warning in Linux replace %d with %zu
        i++;
    }

    return 0;
}

Try it now

How it works #

The following table demonstrates what happens at each iteration of the loop (assuming terms = 5)

Iteration z x y i
After 1st iteration z = x + y = 0 + 1 = 1 x = y = 1 y = z = 1 i = 2
After 2nd iteration z = 1 + 1 = 2 x = 1 y = 2 i = 3
After 3rd iteration z = 1 + 2 = 3 x = 2 y = 3 i = 4
After 4th iteration z = 2 + 3 = 5 x = 3 y = 5 i = 5

Recommended Reading: