Explanation: This Program shows how to print Fibonacci numbers… For input/output, we include the required library.
For each loop iteration, we declare i and n, respectively, depending on how many Fibonacci numbers the user wishes to see.
Entering this number and reading it prompts the user.
For the purpose of holding the first two Fibonacci numbers, 0 and 1, we initialize two variables, a and b.
A loop with n iterations is what we employ. We set the value of i directly to 0 or 1 for the first two times.
We first compute as the total of a and b, then update a and b for each consecutive iteration.
Printing each Fibonacci number as we compute it is done.

#include <stdio.h>

int main() {
    int n, i;
    printf("Enter the number of Fibonacci numbers to print: ");
    scanf("%d", &n);

    int a = 0, b = 1, next;

    for (i = 0; i < n; i++) {
        if (i <= 1) {
            next = i; // The first two Fibonacci numbers are 0 and 1.
        } else {
            next = a + b; // The next number is the sum of the last two.
            a = b; // Update 'a' to the last number.
            b = next; // Update 'b' to the current number.
        }
        printf("%d ", next); // Print the current Fibonacci number.
    }
    printf("\n");
    return 0;
}

Leave a Reply

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

Verified by MonsterInsights