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.

Code

Here is an example of how the program could be implemented:

C
#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;
}

Output

Output
Enter the number of terms: 5
Fibonacci Series: 0 1 1 2 3

It's working

  • The first line, #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.
  • The int main() line defines the main function of the program. This is the entry point of the program, and the code within the curly braces ({}) will be executed when the program runs.
  • In the next lines, We declared 3 variables 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.
  • Then we take the input for the number of terms (n) from the user using scanf() function.
  • Then we use for loop to generate the Fibonacci series and in each iteration, we are printing the value of t1 and updating the value of t1 and t2 using the following line: nextTerm = t1 + t2; t1 = t2; t2 = nextTerm;
  • Finally, we 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.