Simvik

Sum the numbers up to n

Repeat an addition with a loop. An easy embedded C problem (Decisions and loops), run and graded in the browser.

easy · Decisions and loops · loops · for

Return the sum 1 + 2 + ... + n. For n equal to 5 that is 15. If n is 0, the sum is 0.

Use a loop that counts from 1 to n and adds each number to a running total.

Starter code

int sum_to(int n) {
  int total = 0;
  // Add 1, 2, ..., n to total.
  return total;
}

Example tests

Up to five

printf("%d\n", sum_to(5));

Expected output:

15

Up to one

printf("%d\n", sum_to(1));

Expected output:

1

Learn it first

  • Decisions and loops · Choosing with if and switch, repeating with while and for, and the loop that never ends.

More Decisions and loops problems