C program to print Fibonacci series
Learn how to write a C program to print the Fibonacci series up to n terms. This guide includes an explanation of the Fibonacci sequence, a step-by-step algorithm, and complete code examples.
The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, typically starting with 0 and 1. It is a classic example often used to teach recursion and iterative programming techniques. In this article, we will explore how to write a C program to print the Fibonacci series up to a specified number of terms, n.
Understanding the Fibonacci Series
The following recurrence relation defines the Fibonacci series:
The first few terms of the Fibonacci series are:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
Algorithm to Generate Fibonacci Series
To generate the Fibonacci series up to n terms, we can use the following steps:
- Input the number of terms n.
- Initialize the first two terms of the series as 0 and 1.
- Use a loop to calculate each subsequent term as the sum of the previous two terms.
- Print each term as it is calculated.
Write a C program to print Fibonacci series
Here is the complete C program to print the Fibonacci series up to n terms:
#include <stdio.h>
int main() {
int n, first = 0, second = 1, next, i;
// Input the number of terms
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci series up to %d terms:\n", n);
// Print the first two terms of the series
if (n >= 1) printf("%d\n", first);
if (n >= 2) printf("%d\n", second);
// Calculate and print the rest of the terms
for (i = 3; i <= n; i++) {
next = first + second;
printf("%d\n", next);
first = second;
second = next;
}
return 0;
}
Output
Enter the number of terms: 7
Fibonacci series up to 7 terms:
0
1
1
2
3
5
8
Explanation of the Code
- Input the Number of Terms:
scanf("%d", &n);
reads the number of terms n from the user.
- Initialization:
- The first two terms are initialized as
first = 0
andsecond = 1
.
- The first two terms are initialized as
- Printing the First Two Terms:
- The program checks if n is greater than or equal to 1 or 2 and prints the first two terms accordingly.
- Calculating and Printing the Remaining Terms:
- The
for
loop starts from the 3rd term and continues up to the ( n )-th term. - In each iteration,
next
is calculated as the sum offirst
andsecond
. - The
first
andsecond
values are then updated for the next iteration.
- The
Example Runs
Example 1
Enter the number of terms: 5
Fibonacci series up to 5 terms:
0
1
1
2
3
Example 2
Enter the number of terms: 10
Fibonacci series up to 10 terms:
0
1
1
2
3
5
8
13
21
34