A Fibonacci sequence is defined as follows: the first and second terms in the sequence are 0 and 1. Subsequent terms are found by adding the preceding two terms in the sequence. Write a C program to generate the first n terms of the sequence.

Description:

A fibonacci series is defined as follows:

  • The first term in the sequence is 0
  • The second term in the sequence is 1
  • The sub sequent terms 1 found by adding the preceding two terms in the sequence
  • Formula: let t1, t2, ………… tn be terms in fibinacci sequence
  • t1 = 0, t2 = 1
  • tn = tn - 2 + tn - 1 …… where n > 2

Algorithm:

Step 1: Start
Step 2: Read a, b, sum, lengthOfSeries values as integers
Step 3: Set a as 0 and b as 1
Step 4: for counter: 2 to no increment counter by 1
          begin    
          sum ← a + b;
          Print sum
          a ← b;
          b ← sum;
          end
Step 5: Stop

Flowchart:

Program:

#include<stdio.h>
#include<conio.h>
void main()
{
 int a = 0, b = 1, lengthOfSeries = 0, counter, sum = 0;
 clrscr();
 printf("Enter the length of series \n ");
 scanf("%d", &lengthOfSeries);
 printf("Fibonacci series\n");
 printf("%d  %d", a, b);
 for(counter = 2; counter < lengthOfSeries; counter++)
 {
  sum = a + b;
  printf("  %d",sum);
  a = b;
  b = sum;
 }
 getch();
}

Input & Output:

Enter the length of series
15
Fibonacci series
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

Viva Questions:

Q: What is Fibonacci series ?

Ans: A fibonacci series is defined as follows:

  • The first term in the sequence is 0
  • The second term in the sequence is 1
  • The sub sequent terms 1 found by adding the preceding two terms in the sequence
  • Formula: let t1, t2, ………… tn be terms in fibinacci sequence
  • t1 = 0, t2 = 1
  • tn = tn - 2 + tn - 1 …… where n > 2

Q: What are the various types of unconditional statements?

Ans: goto, break and continue

Q: What are the various types of conditional statements?

Ans: if, if else, switch statements

Q: Expand <STDIO.H >?

Ans: standard input output header file