C Program to print Fibonacci series of a given number

C Program to print Fibonacci series of a given number

In this tutorial, you will learn how to write a program to print Fibonacci series of a given number by using for loop.

Before moving to write a program let’s understand what is Fibonacci series.

What is Fibonacci series?

The type of series in which upcoming number is the sum of previous two number, this type of series are said to be Fibonacci series. e.g., 1, 1, 2, 3, 5, 8, 13, 21…….etc.

Formula for Fibonacci series:

Fn = Fn-1 + Fn-2

Example:

Suppose a user enters 4 as an input then the output will be Fibonacci series: “0, 1, 1, 2, 3”.

#include <stdio.h>
int main() {
    int number, first = 0, second = 1, next;
    printf("Enter a positive integer: ");
    scanf("%d", &number);
    printf("Fibonacci series: %d, %d, ", first, second);
    for (int i = 2; i < number; i++) {
        next = first + second;
        printf("%d, ", next);
        first = second;
        second = next;
    }
    return 0;
}

Output:

Enter a positive integer: 4
Fibonacci series: 0, 1, 1, 2, 3