Fibonacci Generator (Loop)

Fibonacci Generator (Loop)

Medium C Looping 29 views
Explanation Complexity

Problem Statement

Print Fibonacci series of n terms using loop (not recursion). Do variables maintaining same as for previous two numbers. Space-efficient approach.

Input Format

An integer n representing the number of terms.


Output Format

Fibonacci series of n terms.

Example

n = 7


0 1 1 2 3 5 8

Constraints

• n ≥ 1

• Use loop only (no recursion)

• Space-efficient (no array)

Concept Explanation

Fibonacci series is generated by adding the previous two numbers to get the next number.

Step-by-Step Explanation

1.Initialize two variables:

• first = 0

• second = 1

2.If n ≥ 1, print first.

3.If n ≥ 2, print second.

4.Run a loop from 3 to n.

5.In each iteration:

• next = first + second

• Print next

• Update first = second

• Update second = next

6.Loop ends after printing n terms.

Concept Explanation

Fibonacci series is generated by adding the previous two numbers to get the next number.

Step-by-Step Explanation

1.Initialize two variables:

• first = 0

• second = 1

2.If n ≥ 1, print first.

3.If n ≥ 2, print second.

4.Run a loop from 3 to n.

5.In each iteration:

• next = first + second

• Print next

• Update first = second

• Update second = next

6.Loop ends after printing n terms.

Input / Output Format

Input Format
An integer n representing the number of terms.


Output Format
Fibonacci series of n terms.
Constraints
• n ≥ 1

• Use loop only (no recursion)

• Space-efficient (no array)

Examples

Input:
n = 7
Output:
0 1 1 2 3 5 8

Example Solution (Public)

C
#include <stdio.h>

int main() {
    int n, i;
    int a = 0, b = 1, c;

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

    if (n <= 0) {
        return 0;
    }

    printf("Fibonacci series:n");

    if (n >= 1)
        printf("%d ", a);

    if (n >= 2)
        printf("%d ", b);

    for (i = 3; i <= n; i++) {
        c = a + b;
        printf("%d ", c);
        a = b;      // shift previous values
        b = c;
    }

    return 0;
}

Official Solution Code

#include <stdio.h>

int main() {
    int n, i;
    int a = 0, b = 1, c;

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

    if (n <= 0) {
        return 0;
    }

    printf("Fibonacci series:n");

    if (n >= 1)
        printf("%d ", a);

    if (n >= 2)
        printf("%d ", b);

    for (i = 3; i <= n; i++) {
        c = a + b;
        printf("%d ", c);
        a = b;      // shift previous values
        b = c;
    }

    return 0;
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.