C bootcamp · Lab 16

Fibonacci sequence

mediumWhile Loop12 minLesson: While Loop

Read the question, write C on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read n and print the first n Fibonacci numbers on one line, separated by spaces.

The sequence starts 0, 1, and each next number is the sum of the two before it. Use long long — Fibonacci grows fast.

Input. One line: an integer n ≥ 1.

Output. n space-separated numbers starting 0 1 1 2 3 …

Constraints

  • 1 ≤ n ≤ 90 (fits in a 64-bit long long).

Examples

Example 1
Input
7
Output
0 1 1 2 3 5 8
Example 2 — Just the first term.
Input
1
Output
0
Hint
  1. Keep two running values a and b; each step the new pair is (b, a + b).
  2. Print each term with %lld and a trailing space.
Show correct code

Peek only after you have tried. You can still Check your own version.

#include <stdio.h>

int main(void) {
  int n;
  scanf("%d", &n);
  long long a = 0, b = 1;
  for (int i = 0; i < n; i++) {
    printf("%lld ", a);
    long long t = a + b;
    a = b;
    b = t;
  }
  printf("\n");
  return 0;
}
main.cC17 · gcc · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.