C Program to Generate Fibonacci Series

C Program to Generate Fibonacci Series

The Fibonacci series is one of the most famous sequences in mathematics and computer science. Each number in the sequence is the sum of the two numbers before it. The series begins with 0 and 1, and from there, every next number is formed by adding the previous two. So, the sequence starts as 0, 1, 1, 2, 3, 5, 8, and so on.

In programming, generating the Fibonacci series is an excellent exercise for beginners because it teaches how to use loops, variables, and logic together. Writing a C program for this sequence using loops helps you understand how iteration works and how values can be reused in calculations. By the end of this tutorial, you will be able to write a complete program that generates the Fibonacci series, and you will also understand how each part of the code works.

Writing the Program with a For Loop

One common way to generate the Fibonacci series is by using a for loop. Let us look at the complete program first:

#include <stdio.h>

int main() {

    int n, first = 0, second = 1, next, i;

    printf("Enter the number of terms: ");
    scanf("%d", &n);

    printf("Fibonacci Series: ");

    for (i = 0; i < n; i++) {

        if (i <= 1)
            next = i;
        else {
            next = first + second;
            first = second;
            second = next;
        }

        printf("%d ", next);

    }

    return 0;

}

This program begins with including the stdio.h header file, which allows us to use printf() and scanf() for input and output. Inside the main() function, we declare variables: n for the number of terms in the series, first and second to hold the first two numbers, next to store the calculated term, and i as the loop counter.

The program asks the user to enter how many terms they want to generate. Using a for loop, the program runs from i = 0 to i < n. If i is 0 or 1, the program directly assigns the value of i to next since the first two terms of the series are always 0 and 1. For values of i greater than 1, the program calculates the next term as the sum of first and second, then updates first and second to move forward in the sequence. The printf() statement displays each term of the Fibonacci series in order.

Writing the Program with a While Loop

You can also generate the Fibonacci series using a while loop. This method is often used when you are not sure how many iterations will be needed or when the loop depends on a condition.

#include <stdio.h>

int main() {

    int n, first = 0, second = 1, next, i = 0;

    printf("Enter the number of terms: ");
    scanf("%d", &n);

    printf("Fibonacci Series: ");

    while (i < n) {

        if (i <= 1)
            next = i;

        else {
            next = first + second;
            first = second;
            second = next;
        }

        printf("%d ", next);
        i++;

    }

    return 0;

}

This program works almost the same as the for loop version, but instead of a for loop, we use a while loop with the condition i < n. We start with i = 0 and increase i by 1 in each iteration. The logic for generating the Fibonacci terms is the same: if the index is less than or equal to 1, we directly use the index as the value; otherwise, we calculate the next term using the previous two terms.

Writing the Program with Recursion

Another interesting way to generate the Fibonacci series is by using recursion. Recursion means that a function calls itself to solve a smaller part of the same problem. In the case of the Fibonacci series, a recursive function can be written to return the nth term by summing the two previous terms.

Here is the complete program using recursion:

#include <stdio.h>

int fibonacci(int n) {

    if (n == 0)
        return 0;

    else if (n == 1)
        return 1;

    else
        return fibonacci(n - 1) + fibonacci(n - 2);

}

int main() {

    int n, i;

    printf("Enter the number of terms: ");
    scanf("%d", &n);

    printf("Fibonacci Series: ");

    for (i = 0; i < n; i++) {
        printf("%d ", fibonacci(i));
    }

    return 0;

}

In this program, the function fibonacci(int n) is defined to return the nth Fibonacci number. If n is 0, the function returns 0. If n is 1, it returns 1. For all other values, it returns the sum of fibonacci(n - 1) and fibonacci(n - 2).

The main() function asks the user for the number of terms. Then, a for loop calls the fibonacci() function for each index i from 0 to n-1 and prints the result. This way, the entire sequence is generated using recursive calls.

The recursive approach is elegant because the definition of the Fibonacci series naturally fits recursion. However, recursion is not very efficient for large values of n because the same values are recalculated many times. For example, calculating fibonacci(40) will involve thousands of repeated calculations.

Comparing Loops and Recursion

Using loops is usually more efficient for generating the Fibonacci series because each term is calculated only once, and the program directly moves forward. On the other hand, recursion is slower but easier to understand conceptually since it mirrors the mathematical definition of Fibonacci numbers.

If you are writing a program for a small number of terms, recursion works fine. But if you need a large number of terms or very big Fibonacci numbers, loops or optimized methods (like dynamic programming) are preferred.

Common Beginner Mistakes

When writing a Fibonacci program, beginners often make these errors:

  • Forgetting to initialize the first two terms (first = 0 and second = 1). Without this, the sequence may start with random or incorrect values.
  • Using the wrong loop condition, such as i <= n instead of i < n, which prints one extra term.
  • Forgetting to update both first and second inside the loop, leading to incorrect values in the sequence.

To avoid these issues, always initialize the first two terms, use the correct loop condition, and ensure both variables are updated properly within the loop.

FAQs

Q1: Can the Fibonacci series be generated without loops?
Yes, it can also be generated using recursion, where a function calls itself to calculate each term. However, recursion can be less efficient than using loops for large numbers of terms.

Q2: Can I generate the Fibonacci series up to a certain value instead of a number of terms?
Yes, instead of running the loop for n terms, you can run it until the next Fibonacci number exceeds the given maximum value.

Q3: Can I use arrays to store the Fibonacci series?
Yes, you can store each calculated term in an array and print them later. This approach is useful if you need to access any specific term later in the program.

Q4: What data type should I use for large Fibonacci numbers?
For small sequences, int is fine. But for larger sequences, use long long int in C, as Fibonacci numbers grow very quickly.

Conclusion

The Fibonacci series is a simple yet important concept in programming. Writing a C program to generate it using loops helps you practice variables, conditions, and iteration. Whether you use a for loop or a while loop, the logic remains the same: start with the first two numbers and keep adding them to generate the next number. By understanding and practicing these methods, you can strengthen your problem-solving skills and move on to more advanced programming challenges.

References & Additional Resources

  1. Kernighan, Brian W., and Dennis M. Ritchie. The C Programming Language. 2nd Edition, Prentice Hall, 1988.
  2. GeeksforGeeks: Fibonacci Series in C – Detailed guide with multiple methods.
  3. Programiz: C Programming Examples – Beginner-friendly examples including Fibonacci.
  4. TutorialsPoint: Loops in C – Explanation of for, while, and do-while loops.
  5. Stack Overflow: Fibonacci Series Implementation – Discussions on different Fibonacci implementations.

Scroll to Top