C bootcamp · Lab 07

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 a non-negative integer n. Print the sum 1 + 2 + … + n.

If n is 0, the sum is 0. You may use a loop or the formula n * (n + 1) / 2.

Input. One integer n.

Output. One integer — the sum.

Constraints

  • 0 ≤ n ≤ 10 000

Examples

Example 1 — 1+2+3+4+5 = 15
Input
5
Output
15
Example 2
Input
1
Output
1
Hint
  1. A while loop: total = 0; i = 1; while (i <= n) { total += i; i++; }
  2. The closed form n * (n + 1) / 2 also works. Watch integer overflow only if n is huge — it is not, here.
Show correct code

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

#include <stdio.h>

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