How to Find the Sum of Elements in an Array in C++?
Last Updated :
26 Feb, 2024
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
- Create a variable named sum and initialize it with 0.
- Run a loop starting from index 0 to N-1.
- Inside the loop, in each iteration, add the current array element to the variable.
- 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++
#include <iostream>
using namespace std;
int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
int n = sizeof (arr) / sizeof (arr[0]);
int sum = 0;
for ( int i = 0; i < n; i++)
sum += arr[i];
cout << "Sum: " << sum << endl;
return 0;
}
|
Time Complexity: O(N), where n is the number of elements in the array.
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...