Fibonacci Series Program in C (Iteration)

In this method, we use one of the C loops to iterate and print the current term. The first two terms, F1 and F2 are handled separately. After that, we use two variables to store the previous two terms and keep updating them as we move to print the next term.

C




// C Program to print the fibonacci series using iteration
// (loops)
#include <stdio.h>
 
// function to print fibonacci series
void printFib(int n)
{
    if (n < 1) {
        printf("Invalid Number of terms\n");
        return;
    }
 
    // when number of terms is greater than 0
    int prev1 = 1;
    int prev2 = 0;
 
    // for loop to print fibonacci series
    for (int i = 1; i <= n; i++) {
        if (i > 2) {
            int num = prev1 + prev2;
            prev2 = prev1;
            prev1 = num;
            printf("%d ", num);
        }
 
        // for first two terms
        if (i == 1) {
            printf("%d ", prev2);
        }
        if (i == 2) {
            printf("%d ", prev1);
        }
    }
}
 
// driver code
int main()
{
 
    int n = 9;
    printFib(n);
    return 0;
}


Output

0 1 1 2 3 5 8 13 21 

Complexity Analysis

Time Complexity: O(n), Because for n number for terms, the loop inside the printFib() function will be executed n times.
Space Complexity: O(1), Because we only used a few variables which don’t depends on the number of terms to be printed.

For more details, refer to the complete article – Program to Find and Print Nth Fibonacci Numbers



Fibonacci Series Program in C

In this article, we will discuss the Fibonacci series and the programs to print the Fibonacci series in C using recursion or loops.

Similar Reads

What is Fibonacci Series?

The Fibonacci series is the sequence where each number is the sum of the previous two numbers of the sequence. The first two numbers of the Fibonacci series are 0 and 1 and are used to generate the Fibonacci series....

Fibonacci Series Program in C (Recursion)

In this method, we will use a function that prints the first two terms, and the rest of the terms are then handled by the other function that makes use of a recursive technique to print the next terms of the sequence....

Fibonacci Series Program in C (Iteration)

...