OneBite.Dev - Coding blog in a bite size

Find The Sum Of All Elements In An Array In C++

Code snippet for how to Find The Sum Of All Elements In An Array In C++ with sample and detail explanation

In programming, arrays serve a vital function by storing multiple values in a single data structure. In C++, you may find yourself in a situation where you need to determine the sum of all elements in an array. This article will guide you on how to achieve this using C++.

Code snippet for Finding the Sum of All Elements in an Array

Here is a simple code snippet that adds up all elements in an array:

#include<iostream>
using namespace std;

int main() {
    int array[] = {1, 2, 3, 4, 5}; 
    int sum = 0;
    
    for(int i=0; i<5; i++)
    {
        sum += array[i];
    }

    cout << "Sum of array elements is: " << sum << endl;
  
    return 0;
}

Code Explanation for Finding the Sum of All Elements in an Array

The C++ program begins by including header files iostream which is used for input and output in C++.

Then, it goes into the main() function where it declares an integer array with five elements {1, 2, 3, 4, 5} and an integer variable sum set to 0. This sum variable will hold the sum of all elements in the array.

int array[] = {1, 2, 3, 4, 5}; 
int sum = 0;

Next, the for loop is used to iterate over the elements of the array.

for(int i=0; i<5; i++)

Inside the loop, the current element array[i] is added to the sum on each iteration.

sum += array[i];

This continues until all elements in the array are processed.

Then, the sum of all elements in the array is printed out using cout.

cout << "Sum of array elements is: " << sum << endl;

Finally, the main() function returns 0, which signifies that the program has finished successfully.

This simple C++ code, therefore, accomplishes the task of adding all elements in an array and can be adjusted depending on the size of your array.

c-plus-plus