In this C++ tutorial, you shall learn how to write a program to find the sum of elements in the given integer array.

C++ Find Sum of Elements in Integer Array

To find the sum of elements in an integer array, loop through the elements of this array using a For Loop or While Loop, and accumulate the sum in a variable.

Examples

ADVERTISEMENT

1. Find sum of integers in the array {2, 4, 6, 8}

In the following example, we take an integer array initialized with some elements, and find the sum of the elements of this array using a For Loop.

main.cpp

#include <iostream>
using namespace std;

int main() {
    int x[] = {2, 4, 6, 8}; //integer array
    int len = sizeof(x) / sizeof(x[0]); //get array length
    int sum = 0; //initialize sum with 0
    
    for (int i = 0; i < len; i++) {
        sum += x[i]; //accumulate sum
    }
    
    cout << "Sum : " << sum << endl;
}

Output

Sum : 20
Program ended with exit code: 0

Conclusion

In this C++ Tutorial, we learned how to find the sum of elements of an integer array, with the help of example C++ programs.