C++ bootcamp · Lab 09

Sum 1 to n

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

Use a long long — for large n the sum overflows a 32-bit int.

Input. One line: an integer n ≥ 0.

Output. One integer: the total.

Constraints

  • 0 ≤ n ≤ 1000000

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 a running total.
  2. The formula n * (n + 1) / 2 needs no loop — but keep it in long long.
Show correct code

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

#include <iostream>

int main() {
  long long n;
  std::cin >> n;
  std::cout << n * (n + 1) / 2 << "\n";
  return 0;
}
main.cppC++17 · g++ · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.