C Program to Display Fibonacci Sequence

In this post, you will learn how to display Fibonacci sequences using the C Programming language.

C Program to Display Fibonacci Sequence

A Fibonacci sequence is a sequence in which the next term is the sum of the previous two terms. For example – 0, 1, 1, 2, 3, 5, 8, 13, 21, . . . etc.

So, without further ado, let’s begin the tutorial.

C Program to Display Fibonacci Sequence

// C Program to Display Fibonacci Sequence
#include <stdio.h>
int main(){
    int i, n, first_term = 0, second_term = 1, next_term;
    
    // Asking for Input
    printf("Enter the number of terms: ");
    scanf("%d", &n);
    
    // logic
    for (i = 0; i < n; i++){
        if (i <= 1)
            next_term = i;
        else {
            next_term = first_term + second_term ;
            first_term = second_term;
            second_term = next_term;
        }
        printf("%d \n", next_term);    
    }
    return 0;
}

Output

Enter the number of terms: 12
0 
1 
1 
2 
3 
5 
8 
13 
21 
34 
55 
89 

How Does This Program Work ?

    int i, n, first_term = 0, second_term = 1, next_term;

In this program, we have declared 5 int type variables named as i, n, first_term, second_term and next_term respectively.

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

Then, the user is asked to enter an integer. The value of the integer will be stored in n.

Some of the used terms are as follow:

#include <stdio.h> – In the first line we have used #include, it is a preprocessor command that tells the compiler to include the contents of the stdio.h(standard input and output) file in the program. 

The stdio.h is a file which contains input and output functions like scanf() and printf() to take input and display output respectively. 

Int main() – Here main() is the function name and int is the return type of this function. The Execution of any Programming written in C language begins with main() function.

scanf() – scanf() function is used to take input from the user.  

printf() – printf() function is used to display and print the string under the quotation to the screen. 

for loop – A loop is used for initializing a block of statements repeatedly until a given condition returns false.

// – Used for Commenting in C. 

Conclusion

I hope after going through this post, you understand how to display a Fibonacci sequence using C Programming language.

If you have any doubt regarding the topic, feel free to contact us in the Comment Section. We will be delighted to help you.

Leave a Comment

Your email address will not be published. Required fields are marked *