c
  1. c-program-to-display-fibonacci-sequence

Program to Display Fibonacci Sequence - ( C Programs )

Example

In this example, we will display the Fibonacci sequence using C language:

#include <stdio.h>

int main()
{
    int n, first = 0, second = 1, next, i;

    printf("Enter the number of terms to display in Fibonacci sequence:\n");
    scanf("%d",&n);

    printf("Fibonacci Series:\n");

    for (i = 0; i < n; i++)
    {
        if (i < 2)
            next = i;
        else
        {
            next = first + second;
            first = second;
            second = next;
        }

        printf("%d ", next);
    }

    return 0;
}

Output

When the above C program is executed, it will produce the following output:

Enter the number of terms to display in Fibonacci sequence:
10
Fibonacci Series:
0 1 1 2 3 5 8 13 21 34

Explanation

This program displays the Fibonacci sequence up to a certain number of terms provided by the user. The first two terms of the sequence are 0 and 1. Every subsequent term is the sum of the two preceding terms.

In the above program, the user is prompted to input the number of terms to be displayed. The program then enters a for loop to calculate and display each term of the sequence. The if statement checks whether the current term being calculated is one of the first two terms. If it is, then the next variable is set to the current term. If it is not one of the first two terms, then the next variable is set to the sum of the two preceding terms.

Use

The Fibonacci sequence is an important mathematical sequence that has a variety of uses in fields such as mathematics, computer science, and engineering. It is often used in algorithms for generating random numbers and in applications that require calculations based on the Golden Ratio.

Summary

In this tutorial, we have learned how to create a C program to display the Fibonacci sequence. We have also examined the logic behind the sequence and how it can be used in various applications.

Published on: