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:
10One element
int v[] = { 5 };
printf("%d\n", sum_values(v, 1));Expected output:
5Learn it first
- Arrays and text · Many values under one name, looping over them safely, and strings.
More Arrays and text problems
- Largest element · Track the best value seen so far.
- Count readings above a threshold · Count the elements that pass a test.
- Fill an array · Write to the elements of an array.
- Find a value · Search an array and report where a value is.
- Average of readings · Combine a loop with integer division.
- Length of a string · Find where a piece of text ends.
- Count a character · Loop over text and count matches.