Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to print the following febonnaci series 0 1 1 2 3 5 8 13 21 ... upto n times

C Code Example — Series Programs

ADVERTISEMENT

C Program to print the following febonnaci series 0 1 1 2 3 5 8 13 21 ... upto n times

Objective

Write a C program to print the Fibonacci series: 0 1 1 2 3 5 8 13 ..... n terms.

Algorithm / Approach

  1. Read the number of terms n.
  2. Initialize two starting variables: a = -1 and b = 1.
  3. Run a loop i from 0 to n-1.
  4. Inside the loop, calculate the next term: c = a + b.
  5. Print c.
  6. Shift the variables forward: a = b and b = c.
main.c
#include<stdio.h>
int main( ){
 int i, a,b,c;
 printf("Enter Value for N : ");
 scanf("%d", &n);
 a = -1;
 b = 1;
 for(i=0; i < n; i++) {
  c = a+b;
  printf("%d ",c);
  a = b;
  b = c;
 }
 printf("\n");
 return 0;
}

Expected Output

Enter Value for N : 8
0 1 1 2 3 5 8 13

Explanation of the Program

  • The Fibonacci series is a famous mathematical sequence where every number is the sum of the two preceding ones.
  • By starting a at -1 and b at 1, the very first loop iteration calculates c = -1 + 1 = 0, perfectly generating the first term of the sequence. Then, shifting the values ensures the next iteration adds 1 + 0 = 1, then 0 + 1 = 1, then 1 + 1 = 2, etc.

Complexity

Time Complexity O(n)
Space Complexity O(1)
ADVERTISEMENT