JavaScript bootcamp · Lab 11

Fibonacci sequence

mediumFor12 minLesson: For

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

QuestionHint and solution stay closed until you open them

Read n and log 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.

Input. One line: an integer n ≥ 1.

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

Constraints

  • 1 ≤ n ≤ 50

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. Array destructuring advances the pair in one line: [a, b] = [b, a + b].
  2. Collect terms in an array, then join with a space.
Show correct code

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

const n = Number(readLine());
let a = 0, b = 1;
const seq = [];
for (let i = 0; i < n; i++) {
  seq.push(a);
  [a, b] = [b, a + b];
}
console.log(seq.join(" "));
main.jsconsole.log · readLine() · Ctrl + Enter
ResultIdle
Run to see output. Check grades the tests.