Beginner C/C++ Exercises

Sum Array Values

An accumulator reduces a sequence to one total.

What is Sum Array Values?

An accumulator reduces a sequence to one total.

Calculate the sum of all values in an array.

Important points

  • Compile with warnings enabled and fix every warning.
  • Know the lifetime and type of every value.
  • Validate input and keep array bounds explicit.

C and C++ code examples

C
Run code →
main.c
#include <stdio.h>
int main(void) {
    int values[] = {2, 4, 6, 8, 10}; int total = 0;
    // sizeof determines the local array length.
    for (size_t i = 0; i < sizeof values / sizeof values[0]; ++i) total += values[i];
    printf("sum=%d\n", total);
}
Expected output
sum=30
C++
Run code →
main.cpp
#include <iostream>
#include <numeric>
#include <vector>
int main() {
    std::vector values{2, 4, 6, 8, 10};
    // accumulate folds the range into one total.
    std::cout << "sum=" << std::accumulate(values.begin(), values.end(), 0) << '\n';
}
Expected output
sum=30

C and C++ comparison

Initialize the total to zero and add every element exactly once.

C

C exposes small procedural APIs and makes representation details explicit.

C++

C++ retains the low-level model while adding safer library types and abstractions.

Practice exercises

Run both versions, then modify them to observe the different language guarantees.

  • Add invalid and boundary-value inputs.
  • Compile with -Wall -Wextra -Wpedantic.
  • Move reusable declarations into a header and implementation file.