JavaScript bootcamp · Lab 09

Sum 1 to n

easyWhile10 minLesson: While

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 1 + 2 + … + n. If n is 0, log 0.

You can loop, or use the Gauss formula n(n+1)/2 — try both and confirm they agree.

Input. One line: an integer n ≥ 0.

Output. One integer: the total.

Constraints

  • 0 ≤ n ≤ 100000

Examples

Example 1 — 1+2+3+4+5.
Input
5
Output
15
Example 2
Input
1
Output
1
Hint
  1. A while loop can accumulate into a total.
  2. The formula n * (n + 1) / 2 needs no loop.
Show correct code

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

const n = Number(readLine());
console.log(n * (n + 1) / 2);
main.jsconsole.log · readLine() · Ctrl + Enter
ResultIdle
Run to see output. Check grades the tests.