C Workshop · Sum of Array
Lesson C

Sum of Array

Add every element into a running total, then print once.

What it is

Summing an array is a running total over indexes 0 through n-1. Start at 0, add each a[i], print once at the end.

Approach

  1. Fill the array (or read it).
  2. sum = 0, then sum += a[i] for each i.
  3. Print sum.

Where this is used in the real world

Diagram

1

0

sum

2

+1

1

3

+8

9

4

+3 +5

17

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 a[4] = {1, 8, 3, 5};
4    int i, sum = 0;
5    for (i = 0; i < 4; i++) {
6        sum = sum + a[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. 1+8+3+5 =

17.

2. sum starts at 0 so that:

Identity for addition.

3. The loop runs i from:

0 .. n-1.

4. Printing inside the loop would show:

Print after for the final total.

5. For a 2-D matrix sum you would:

Rows then columns.