English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C Language Basic Tutorial

C Language Flow Control

C Language Functions

C Language Arrays

C Language Pointers

C Language Strings

C Language Structures

C Language Files

C Others

C Language Reference Manual

C program to display the Fibonacci sequence

Comprehensive Collection of C Programming Examples

In this example, you will learn to display the Fibonacci sequence of the first n numbers (input by the user).

To understand this example, you should understand the followingC programmingTopic:

The Fibonacci sequence is a sequence where the next term is the sum of the previous two terms. The first two terms of the Fibonacci sequence are 0, followed by1.

The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21

The n-th term of the Fibonacci sequence

#include <stdio.h>
int main() {
    int i, n, t1 = 0, t2 = 1, nextTerm;
    printf("Enter the number of terms: ");
    scanf("%d", &n);
    printf("Fibonacci sequence: ");
    for (i = 1; i <= n; ++i) {
        printf("%d, ", t1);
        nextTerm = t1 + t2;
        t1 = t2;
        t2 = nextTerm;
    }
    return 0;
}

Output Result

Enter the number of terms: 10
Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

Fibonacci sequence up to a certain number

#include <stdio.h>
int main() {
    int t1 = 0, t2 = 1, nextTerm = 0, n;
    printf("Enter a positive number: ");
    scanf("%d", &n);
    //Display the first two terms, which are always 0 and1
    printf("Fibonacci Series: %d, %d, ", t1, t2);
    nextTerm = t1 + t2;
    while (nextTerm <= n) {
        printf("%d, ", nextTerm);
        t1 = t2;
        t2 = nextTerm;
        nextTerm = t1 + t2;
    }
    return 0;
}

Output Result

Enter a positive integer: 100
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,

Comprehensive Collection of C Programming Examples