easy
0 views

Python Program To Print Fibonacci Sequence

Generate and print the first N terms of the Fibonacci sequence starting with 0 and 1

Understand the Problem

Problem Statement

Given an integer N, generate and print the first N terms of the Fibonacci sequence. The Fibonacci sequence starts with 0 and 1, where each subsequent term is the sum of the two preceding terms.

For example: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

Constraints

  • 3 ≤ N ≤ 50
  • N must be a positive integer
  • Output terms must be space-separated
  • Sequence must start with 0, 1

Examples

Example 1
Input
5
Output
0 1 1 2 3
Explanation

The first 5 terms of the Fibonacci sequence are: 0, 1, 1, 2, 3

Example 2
Input
10
Output
0 1 1 2 3 5 8 13 21 34
Explanation

The first 10 terms of the Fibonacci sequence are: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34

Solution

#include <stdio.h>

int main() {
    int n;
    scanf("%d", &n);
    
    int n1 = 0, n2 = 1;
    
    for (int i = 0; i < n; i++) {
        if (i == 0) {
            printf("%d", n1);
        } else if (i == 1) {
            printf(" %d", n2);
        } else {
            int next = n1 + n2;
            printf(" %d", next);
            n1 = n2;
            n2 = next;
        }
    }
    
    printf("\n");
    return 0;
}
Time:O(N) - single loop through N terms
Space:O(1) - only uses a few integer variables
Approach:

This C solution uses a for loop to generate the Fibonacci sequence:

  • Initialize n1=0, n2=1 as the first two terms
  • Use a loop that runs N times
  • Handle first two terms separately for correct output formatting
  • For subsequent terms, calculate next term and update variables
  • Print each term with proper spacing

Visual Explanation

Loading diagram...