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
- Read the number of terms
n. - Initialize two starting variables:
a = -1andb = 1. - Run a loop
ifrom 0 ton-1. - Inside the loop, calculate the next term:
c = a + b. - Print
c. - Shift the variables forward:
a = bandb = 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
aat -1 andbat 1, the very first loop iteration calculatesc = -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)