Contact Learn C
Copy

Program 19:To print Fibonacci Series.

Program 19:                                                                                         What is fibonacci series?
#include<stdio.h>
main()
{
 int a=0,b=1,num,c,count;
 printf("Enter a number to obtain fibonacci series\n");
 scanf("%d",&num);
 printf("The series is\n");
 printf("%d \n%d\n",a,b);
 count=2;
 while(count<num)
 {
   c=a+b;
   a=b;
   b=c;
   printf("%d\n",c);
   count++;
 }
}
Explanation:
  1. The program starts with intializing
    • a - for storing starting number of series
    • b - for storing second number of series
    • num- for storing the length of series
    • c - for temporary(auxiliary) variable
    • count-for storing the number of iterations that the loop has undergone
  2. First we print the first two values of series i.e. a and b Now the series is 0,1 before starting fibonacci series
  3. Now the count is stored with value 2(count=2)
  4. The while loop iterates until the count is less than given number num(lenght of series)
    • step-1 : Now if num=8(say) ,count=2,a=0,b=1 .
    • step-2 : as count is less than count (2 is less than 8 )→ true
      • c=0+1=1 → c=1
      • a=b → a=1
      • b=c → b=1
      • Then c is printed and now series is 0,1,1
      • Then count is incremented → count=3
      • Now values are c=1,a=1,b=1,count=3
    • step-3 : as count is less than count(3 is less than 8 ) → true
      • c=a+b=1+1→ c=2
      • a=b → a=1
      • b=c → b=2
      • Then c is printed and now series is 0,1,1,2
      • Then count is incremented → count=4
      • Now values are c=2,a=1,b=2,count=4
    • step-4 : as count is less than count(4 is less than 8 ) → true
      • c=a+b=1+2→ c=3
      • a=b → a=2
      • b=c → b=3
      • Then c is printed and now series is 0,1,1,2,3
      • Then count is incremented → count=5
      • Now values are c=3,a=2,b=3,count=5
    • step-5 : as count is less than count(5 is less than 8 ) → true
      • c=a+b=2+3→ c=5
      • a=b → a=3
      • b=c → b=5
      • Then c is printed and now series is 0,1,1,2,3,5
      • Then count is incremented → count=6
      • Now values are c=5,a=3,b=5,count=6
    • step-6 : as count is less than count(6 is less than 8 ) → true
      • c=a+b=3+5→ c=8
      • a=b → a=5
      • b=c → b=8
      • Then c is printed and now series is 0,1,1,2,3,5,8
      • Then count is incremented → count=7
      • Now values are c=8,a=5,b=8,count=7
    • step-7 : as count is less than count(7 is less than 8 ) → true
      • c=a+b=5+8→ c=13
      • a=b → a=8
      • b=c → b=13
      • Then c is printed and now series is 0,1,1,2,3,5,8,13
      • Then count is incremented → count=8
      • Now values are c=13,a=8,b=13,count=8
    • step-8: as count is not less than count(8 is less than 8 ) → false
    • So the final series is 0,1,1,2,3,5,8,13.
Output:
Print Fibonacci Series
Donate

Download App and Learn when ever you want

Get it on PlayStore
Get it on Amazon App Store
Get it on Aptoide