Simvik

Sum an array

Visit every element with a loop. An easy embedded C problem (Arrays and text), run and graded in the browser.

easy · Arrays and text · arrays · loops

An array is a row of values of the same type, numbered from 0. A function that receives one also needs to be told how many elements it has.

Return the sum of the first n elements of values.

Starter code

int sum_values(const int values[], int n) {
  int total = 0;
  // Add values[0], values[1], ..., values[n - 1].
  return total;
}

Example tests

Four elements

int v[] = { 1, 2, 3, 4 };
printf("%d\n", sum_values(v, 4));

Expected output:

10

One element

int v[] = { 5 };
printf("%d\n", sum_values(v, 1));

Expected output:

5

Learn it first

  • Arrays and text · Many values under one name, looping over them safely, and strings.

More Arrays and text problems