Fibonacci Series Program In C


Advertisements

Fibonacci Series generates subsequent number by adding two previous numbers. Fibonacci series starts from two numbers − F0 & F1. The initial values of F0 & F1 can be taken 0, 1 or 1, 1 respectively.

Fibonacci series satisfies the following conditions −

Fn = Fn-1 + Fn-2

So a Fibonacci series can look like this −

F8 = 0 1 1 2 3 5 8 13

or, this −

F8 = 1 1 2 3 5 8 13 21

Algorithm

Algorithm of this program is very easy −

START
   Step 1 → Take integer variable A, B, C
   Step 2 → Set A = 0, B = 0
   Step 3 → DISPLAY A, B
   Step 4 → C = A + B
   Step 5 → DISPLAY C
   Step 6 → Set A = B, B = C
   Step 7 → REPEAT from 4 - 6, for n times
STOP

Pseudocode

procedure fibonacci : fib_num
   
   IF fib_num less than 1
      DISPLAY 0
      
   IF fib_num equals to 1
      DISPLAY 1
      
   IF fib_num equals to 2
      DISPLAY 1, 1
      
   IF fib_num greater than 2
      Pre = 1,
      Post = 1,
      
      DISPLAY Pre, Post
      FOR 0 to fib_num-2
         Fib = Pre + Post
         DISPLAY Fib
         Pre = Post
         Post = Fib
      END FOR
   END IF

end procedure

Implementation

Implementation of this algorithm is given below −

#include <stdio.h>

int main() {
   int a, b, c, i, n;

   n = 4;

   a = b = 1;
   
   printf("%d %d ",a,b);

   for(i = 1; i <= n-2; i++) {
      c = a + b;
      printf("%d ", c);
      
      a = b;
      b = c;
   }
   
   return 0;
}

Output

Output of the program should be −

1 1 2 3
mathematical_programs_in_c.htm
Advertisements