Fibonacci Series Program in C

Write a C program to find Fibonacci series up to n

The sequence is a Fibonacci series where the next number is the sum of the previous two numbers. The first two terms of the Fibonacci sequence is started from 0,1,…

  • Example: limit is Fibonacci series 8
  • Sequence is 0,1,1,2,3,5,8,13

Its followed on addition operation. Next number is the addition of before the first two numbers.

Fibonacci series upto n terms in c

Working:-

Step 1.Initialize variables limit, N1=0, N2=1, N3, i.

Step 2.To take user input for limit of serious.

Step 3.Display N1, N2 value .

Step 4.We use for loop with the condition(i=0;i<limit).

Step 5.Compute N3 = N1 + N2 and n1=n2.  && n2=n3.

Step 6.Than display N3 as output and close the loop

Step 7.Stop

Fibonacci series

C Program:-

#include<stdio.h>
int main()
{
//To initialize variables
int n1=0,n2=1,n3,limit,i;

//To take user input
printf("enter a limit of series \n");
scanf( "%d",&limit);

printf("Fibonacci series %d %d ",n1,n2);

//To use this loop for given length
for(i=2;i<limit;i++)
{
//n1 and n2 sum store in new variable n3
n3=n1+n2;
n1=n2;
n2=n3;
//display serious
printf("%d ",n3);
}
return 0;
}

Output:-

enter a limit of series 
7
Fibonacci series 0 1 1 2 3 5 8

Alternate Approach


/**C program to print Fibonacci series up to n terms*/ 
#include<stdio.h>
int main()
{
    int a, b, c, i, terms;
/* Ask number from user */ 
    printf("Insert number of terms: ");
    scanf("%d", &terms);
/* Variable initialization */
    a = 0;
    b = 1;
    c = 0;
    printf("Fibonacci terms: \n");
/* repeat the loop to n terms */
    for(i=1; i<=terms; i++)
    {
        printf("%d ", c);
        a = b;     // Copy n-1 to n-2
        b = c;     // Copy current to n-1
        c = a + b; // New term
    }
    return 0;
}

Output

Insert number of terms: 7
Fibonacci terms: 
0 1 1 2 3 5 8