Write a C program to print the Fibonacci series
Description: Take the number of terms as input. Print that many terms of the Fibonacci series: 0, 1, 1, 2, 3, 5, 8 …
Hint:
- Each term is the sum of the two terms before it.
C program to print the Fibonacci series
#include <stdio.h>
int main(void) {
int n, a = 0, b = 1, next;
printf("Enter number of terms: ");
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
printf("%d ", a);
next = a + b;
a = b;
b = next;
}
printf("\n");
return 0;
}
Output:
Output of the above program is
Enter number of terms: 8
0 1 1 2 3 5 8 13
How it works
- We start with
a = 0andb = 1. - In each round we print
a, then move forward:atakes the value ofb, andbtakes the new sum.
Learn more about the similar topics:
| Tutorials |
|---|
| C If Else Statement |
| C Else If Ladder and Nested If |
| C Switch Statement |
| C While Loop |
| C Do While Loop |
| C For Loop |
| C Nested Loops |