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. The sequence looks like this:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

Logic to Generate Fibonacci Series:

  1. Start with the first two numbers in the Fibonacci series, typically 0 and 1.
  2. For the next number, sum the two preceding numbers.
  3. Repeat the process for the desired count of numbers in the series.

Program:

Here’s a simple C program to print the Fibonacci series up to a specified number of terms:

#include <stdio.h> int main() { int n, i, t1 = 0, t2 = 1, nextTerm; // Input the number of terms from the user printf("Enter the number of terms: "); scanf("%d", &n); printf("Fibonacci Series: "); // Print the first two terms for (i = 1; i <= n; ++i) { if (i == 1) { printf("%d, ", t1); // First term continue; } if (i == 2) { printf("%d, ", t2); // Second term continue; } nextTerm = t1 + t2; // Calculate the next term t1 = t2; // Update t1 to the second term t2 = nextTerm; // Update t2 to the new term printf("%d, ", nextTerm); // Print the next term } return 0; }

Explanation:

  1. Variables:

    • int n: This variable holds the number of terms in the Fibonacci series that the user wants to print.
    • int i: This is a loop counter.
    • int t1: This variable holds the first term in the series (initialized to 0).
    • int t2: This variable holds the second term in the series (initialized to 1).
    • int nextTerm: This variable is used to calculate the next term in the series.
  2. Input:

    • The program prompts the user to enter the number of terms (n) they want in the Fibonacci series.
  3. Fibonacci Calculation:

    • A for loop runs from 1 to n to generate the Fibonacci series.
    • First and Second Terms: The program prints the first two terms (0 and 1) separately.
    • Calculating Next Terms:
      • For subsequent terms, the program calculates the next term as the sum of the previous two terms: nextTerm = t1 + t2.
      • It then updates t1 and t2 to move to the next pair in the series.
      • The program prints each nextTerm.
  4. Output:

    • The Fibonacci series is printed in a comma-separated format.

Sample Output:

Example 1:

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

Example 2:

Enter the number of terms: 10 Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

Key Points:

  • Iterative Approach: This program uses a simple iterative approach to generate the Fibonacci series.
  • Variable Updates: The use of t1 and t2 helps keep track of the last two terms, making it easy to compute the next term.
  • Basic Concepts: This program demonstrates basic programming concepts such as loops, conditionals, and input/output in C.