C program to Generate First n Fibonacci Numbers

Spread the love
In my previous blog post we discussed about what is Fibonacci series also we written one program to Generate Fibonacci series upto given Number. Today in this post we will discuss about another program on Fibonacci series. that is C Program to Generate First n fibonacci Numbers (n is integer value)

Description :

This program accepts one number from user, let’s say it as n and prints first n Fibonacci Numbers on Console.

Program :

  1. /*
  2.         C Program to Generate first n Fibonacci Numbers
  3.         this program accepts one number from user let’s say it as n
  4.         and prints first n Fibonacci Numbers on Console.
  5.         Author  :       Venkatesh Macha
  6. */
  7. #include<stdio.h>
  8. int main()
  9. {
  10.         int i,j,k,num,cnt;
  11.         printf(“How many fibonacci numbers do you want to print : “);
  12.         scanf(“%d”,&num);
  13.         i=0;
  14.         j=1;
  15.         /* because fibonacci series starts with 0,1
  16.          * so i initialized i and j as 0 and 1
  17.          */
  18.         printf(“Fibonacci Series is : “);
  19.         if(num == 1)
  20.         {
  21.                 printf(” %dn,i);
  22.                 return;
  23.         }
  24.         printf(” %d %d “,i,j);
  25.         cnt=2;
  26.         // cnt=2 because we already printed i,j in above statement.
  27.         k=i+j;
  28.         while(num > cnt)
  29.         {
  30.                 printf(“%d “,k);
  31.                 i=j;
  32.                 j=k;
  33.                 k=i+j;
  34.                 cnt++;
  35.         }
  36.         printf(n);
  37. }

Output :

Note : This program generates up to any number of Fibonacci Series but You need to use sufficient Datatype for the our i,j,k variables. In above program i used Integer datatype for i,j,k variables, So it will generates up to 2 giga number after that it will give Negative numbers. So Use Long int or Long long int depending on your Requirement. You can refer this post to know the basic Datatypes in and Size of those Datatypes.

More Programs on Fibonacci Series :

More C Programs :


Hi Guys, I am Venkatesh. I am a programmer and an Open Source enthusiast. I write about programming and technology on this blog.

You may also like...

Leave a Reply