Open In App

How to Find the Sum of Elements in an Array in C++?

Last Updated : 26 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, an array is the collection of similar data elements that are stored in the contiguous memory location and we can access these elements directly by their index value. In this article, we will learn how to find the sum of elements in an array in C++.

Example:

Input:
 myVector = {1, 2, 3, 4, 5}

Output:
Sum = 15

Find the Sum of Values in an Array in C++

We can find the sum of all elements in an array in C++ by using a loop and keep adding each element to the collective sum:

Approach

  1. Create a variable named sum and initialize it with 0.
  2. Run a loop starting from index 0 to N-1.
  3. Inside the loop, in each iteration, add the current array element to the variable.
  4. When the loop terminates, the sum variable will contain the sum of all the values in the array.

C++ Program to Find the Sum of Values in an Array

C++




// C++ program to find the sum of all elements in an array
#include <iostream>
using namespace std;
  
int main()
{
    // Initialize the array
    int arr[] = { 1, 2, 3, 4, 5 };
  
    // size of the array
    int n = sizeof(arr) / sizeof(arr[0]);
  
    // sum of the array elements
    int sum = 0;
    for (int i = 0; i < n; i++)
        sum += arr[i];
  
    cout << "Sum: " << sum << endl;
  
    return 0;
}


Output

Sum: 15

Time Complexity: O(N), where n is the number of elements in the array.
Auxiliary Space: O(1)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads