Generate a Fibonacci Sequence in C

CCBeginner
Practice Now

Introduction

In this lab, we will learn how to generate a Fibonacci sequence in C. The Fibonacci sequence is a well-known mathematical sequence where each number is the sum of the two preceding ones. We will start by reading the number of terms from the user, then use a loop to generate the sequence, and finally print the resulting Fibonacci sequence. This lab covers fundamental concepts in number theory and discrete mathematics using the C programming language.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c/UserInteractionGroup -.-> c/output("`Output`") c/BasicsGroup -.-> c/variables("`Variables`") c/ControlFlowGroup -.-> c/for_loop("`For Loop`") c/UserInteractionGroup -.-> c/user_input("`User Input`") subgraph Lab Skills c/output -.-> lab-435187{{"`Generate a Fibonacci Sequence in C`"}} c/variables -.-> lab-435187{{"`Generate a Fibonacci Sequence in C`"}} c/for_loop -.-> lab-435187{{"`Generate a Fibonacci Sequence in C`"}} c/user_input -.-> lab-435187{{"`Generate a Fibonacci Sequence in C`"}} end

Read Number of Terms

In this step, we will learn how to read the number of terms for generating a Fibonacci sequence in C. This is the first crucial step in creating our Fibonacci sequence program.

First, let's create a new C file in the ~/project directory:

cd ~/project
nano fibonacci.c

Now, let's write the initial code to read the number of terms from the user:

#include <stdio.h>

int main() {
    int n;

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

    printf("You entered %d terms.\n", n);

    return 0;
}

Let's compile and run the program to test our input:

gcc fibonacci.c -o fibonacci
./fibonacci

Example output:

Enter the number of terms in Fibonacci sequence: 10
You entered 10 terms.
Explanation
  • scanf("%d", &n) reads an integer input from the user and stores it in the variable n
  • We use printf() to prompt the user and display the number of terms entered
  • The program validates that we can successfully capture user input for the sequence length

Use a Loop to Generate Terms

In this step, we will modify our previous Fibonacci sequence program to generate the sequence using a loop. We'll build upon the code from the previous step to create the actual Fibonacci sequence.

Let's update the fibonacci.c file:

cd ~/project
nano fibonacci.c

Now, let's modify the code to generate Fibonacci terms using a for loop:

#include <stdio.h>

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

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

    printf("Fibonacci Sequence of %d terms: \n", n);

    for (int i = 0; i < n; i++) {
        if (i <= 1)
            next = i;
        else {
            next = first + second;
            first = second;
            second = next;
        }
        printf("%d ", next);
    }
    printf("\n");

    return 0;
}

Compile and run the program:

gcc fibonacci.c -o fibonacci
./fibonacci

Example output:

Enter the number of terms in Fibonacci sequence: 10
Fibonacci Sequence of 10 terms:
0 1 1 2 3 5 8 13 21 34
Explanation
  • We initialize first and second as the first two terms of the Fibonacci sequence
  • The for loop generates subsequent terms by adding the previous two terms
  • next = first + second calculates the next term
  • We update first and second in each iteration to maintain the sequence progression
  • The loop continues until we generate the specified number of terms

Print the Sequence

In this final step, we'll enhance our Fibonacci sequence program by adding formatting options and improving the output presentation.

Let's update the fibonacci.c file to improve sequence printing:

cd ~/project
nano fibonacci.c

Modify the code to add more formatting and printing options:

#include <stdio.h>

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

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

    printf("Fibonacci Sequence of %d terms:\n", n);

    printf("Index\tValue\n");
    printf("-----\t-----\n");

    for (int i = 0; i < n; i++) {
        if (i <= 1)
            next = i;
        else {
            next = first + second;
            first = second;
            second = next;
        }
        printf("%d\t%d\n", i, next);
    }

    return 0;
}

Compile and run the program:

gcc fibonacci.c -o fibonacci
./fibonacci

Example output:

Enter the number of terms in Fibonacci sequence: 8
Fibonacci Sequence of 8 terms:
Index   Value
-----   -----
0       0
1       1
2       1
3       2
4       3
5       5
6       8
7       13
Explanation
  • We added a formatted table with index and value columns
  • \t is used for tab-separated columns to create a neat table layout
  • Each term is now printed with its corresponding index
  • The output provides a clear, structured view of the Fibonacci sequence

Summary

In this lab, we learned how to read the number of terms from the user to generate a Fibonacci sequence in C. We first prompt the user to enter the desired number of terms, then use a loop to calculate and print the Fibonacci sequence. The key steps involve initializing the first two Fibonacci numbers, and then updating them in each iteration of the loop to generate the next number in the sequence.

Finally, we print out the complete Fibonacci sequence based on the user's input. This lab provides a practical example of using loops and variables to generate a classic mathematical sequence in a programming language.

Other C Tutorials you may like