The Fibonacci series is a sequence of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. In this tutorial, we will write a C program to print the Fibonacci series within a given range.
Here is an example of how the program could be implemented:
#include <stdio.h>
int main() {
int i, n, t1 = 0, t2 = 1, nextTerm;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: ");
for (i = 1; i <= n; ++i) {
printf("%d ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return 0;
}
Enter the number of terms: 5
Fibonacci Series: 0 1 1 2 3
#include <stdio.h>
, is a preprocessor directive that tells the compiler to include the contents of the standard input/output header file (stdio.h) in the program.i,n,t1,t2 and nextTerm
. t1
and t2
initialized with 0 and 1 respectively. nextTerm
variable will store the next term of the Fibonacci series.n
) from the user using scanf()
function.t1
and updating the value of t1
and t2
using the following line: nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
return 0
from the main
function.To further customize the program and print the Fibonacci series in a given range, You can add additional conditional statements inside the loop to check if the current number is in the range if it is then print it otherwise skip it.
Additionally, you can prompt the user for the range rather than the number of terms, and use those as the start and stop conditions for the loop.
This program will output the Fibonacci series of the given range on the screen.