Fibonacci series: Write a C language program to generate and print the fibonacci series

The Fibonacci series is a sequence of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. In mathematical terms, the Fibonacci sequence is defined by the recurrence relation:

F(n)=F(n−1)+F(n−2)

with initial conditions:

F(0)=0, F(1)=1

So, the Fibonacci sequence begins: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, and so on.

Each number in the Fibonacci sequence is called a Fibonacci number. The sequence is named after the Italian mathematician Leonardo Fibonacci, who introduced it to the Western world in his book “Liber Abaci” in 1202. The Fibonacci sequence has numerous applications in mathematics, computer science, nature, and art. It often appears in various natural phenomena, such as the arrangement of leaves on a stem, the branching of trees, and the spirals in seashells and galaxies.

Below is a simple C program to generate and print the Fibonacci series up to a specified number of terms.

#include <stdio.h>

// Function to generate and print Fibonacci series
void generateFibonacci(int n) {
    int first = 0, second = 1, next;

    printf("Fibonacci Series up to %d terms: \n", n);

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

int main() {
    int numTerms;

    // Read the number of terms from the user
    printf("Enter the number of terms for Fibonacci series: ");
    scanf("%d", &numTerms);

    // Check for valid input
    if (numTerms <= 0) {
        printf("Please enter a positive integer for the number of terms.\n");
        return 1; // Exit with an error code
    }

    // Generate and print the Fibonacci series
    generateFibonacci(numTerms);

    return 0; // Exit successfully
}

This program prompts the user to enter the number of terms they want in the Fibonacci series, and then it generates and prints the series accordingly. The generateFibonacci function is responsible for computing and printing the series.

Read my other blogs:

C Program to find Given Number is Prime or not.

Write a program to find Factorial Numbers of a given numbers.

Embedded C language Interview Questions.

Automotive Interview Questions

Understanding AUTOSAR Architecture: A Guide to Automotive Software Integration

What is AUTOSAR

MCAL Layer in AUTOSAR

Types of ECU in CAR

Big Endian and Little Endian in Memory

Zero to Hero in C language Playlist

Embedded C Interview Questions

Subscribe my channel on Youtube: Yogin Savani