Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors

Write a program that asks the user to enter a number N and then prints the first N numbers in the Fibonacci sequence

C
#include <stdio.h>

int main() {
    int n, i;
    long long int fib1 = 0, fib2 = 1, fib3;

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

    printf("Fibonacci Sequence: ");

    // Special case for first two terms
    if (n >= 1) {
        printf("%lld ", fib1);
    }
    if (n >= 2) {
        printf("%lld ", fib2);
    }

    // Generate and print the remaining terms
    for (i = 3; i <= n; i++) {
        fib3 = fib1 + fib2;
        printf("%lld ", fib3);
        fib1 = fib2;
        fib2 = fib3;
    }

    printf("\n");

    return 0;
}

Explanation:

  • In this program, we declare variables n and i. fib1 and fib2 are used to store the current and next terms in the Fibonacci sequence, respectively. fib3 is used to calculate the new term.
  • The program asks the user to enter the number of terms they want to print (N).
  • It then prints the first two terms (fib1 and fib2) separately.
  • After that, it generates and prints the remaining terms using a for loop.

Output:

Output
Enter the number of terms: 9
Fibonacci Sequence: 0 1 1 2 3 5 8 13 21 

Why long long int in above program ?

  • This program assumes that N is a positive integer.
  • It uses the long long int data type to handle large Fibonacci numbers.