C++ bootcamp · Lab 11

Fibonacci sequence

mediumFor Loop12 minLesson: For 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 followed by a space, then a newline.
Show correct code

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

#include <iostream>

int main() {
  int n;
  std::cin >> n;
  long long a = 0, b = 1;
  for (int i = 0; i < n; i++) {
    std::cout << a << " ";
    long long t = a + b;
    a = b;
    b = t;
  }
  std::cout << "\n";
  return 0;
}
main.cppC++17 · g++ · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.