C Workshop · Sum 1 to N
Lesson C

Sum 1 to N

Add every integer from 1 through n into a running total.

What it is

A running total starts at zero. Each pass of the loop adds the next integer. When the loop finishes you print once — the finished sum, not the partials.

Approach

  1. Read n. Set sum = 0.
  2. for i from 1 to n, add i.
  3. Print sum.

Where this is used in the real world

Diagram

1

sum=0

start

2

+1 +2 +3 +4

loop

3

10

print

Run algorithm

Each step highlights the matching C line. Program output appears only when a line that prints actually runs.

Ready
C code
1#include <stdio.h>
2int main(void) {
3    int n, i, sum = 0;
4    scanf("%d", &n);
5    for (i = 1; i <= n; i++) {
6        sum = sum + i;
7    }
8    printf("%d\n", sum);
9    return 0;
10}
What this line does
Press Run algorithm. The highlight will move through the C code.
Program output
(no output yet)

Check your understanding

Five questions. Pick one answer each, then Check answers. The correct choice turns green.

1. n = 4 prints:

1+2+3+4=10.

2. sum starts at:

Empty total.

3. If you printf inside the loop you would get:

Print once after.

4. This running total is a:

for i = 1..n.

5. while (i <= n) { sum += i; i++; } compared to for:

Equivalent pattern.