Sum of elements in an Array
Let's look at the C++ program to calculate the sum of elements in an array.
Step 1: Define a numerical array/input the array from the user.
Step 2: Define a variable sum with a value of 0.
Step 3: Traverse over the array from start to finish and add all the array elements into our 'sum' variable.
Step 4: Print or return the calculated sum of elements.
Code
#include <iostream>
using namespace std;
// Function to calculate the sum of elements in an array
int calcSum(int arr[], int n)
{
int sum = 0; // initialize sum
// Traverse through all the elements of array
for (int i = 0; i < n; ++i)
sum += arr[i];
return sum;
}
int main()
{
int arr[] = {11, 12, 13, 15};
// To calculate size of array
int n = sizeof(arr) / sizeof(arr[0]);
cout << "The sum of elements in the array is " << calcSum(arr, n);
return 0;
}
You can also try this code with Online C++ Compiler
Run Code
Output
The sum of elements in the array is 51
Try and compile by yourself with the help of online C++ Compiler for better understanding.
Time complexity
The time complexity of the above approach to find the sum of elements in an array is O(N), where N is the number of array elements
Space complexity
The space complexity of the above approach is O(1) since no extra space is utilized to calculate the sum of elements in an array.
Also read - Decimal to Binary c++
FAQs
-
Can we calculate the sum of floating-point numbers present in an array?
Yes, we can calculate the sum of elements with decimal places present. We need to declare our 'sum' variable as float. The rest of the steps remains the same.
-
How can we calculate the sum of elements in an array using STL?
Standard template library provides a function named accumulate(arr, arr+size, initial_sum) that intake array begin reference, end reference, and initial sum as three parameters and returns the sum of all the array elements.
Time complexity remains the same as O(size).
Key Takeaways
In this article, we have extensively discussed the most common approach to finding the sum of elements in an array.
We hope this blog has helped you enhance your knowledge. For learning more about coding in C++ or other problems like the Program To Print All Permutations Of A Given String or find the factorial of a number, check out Code Studio's blog site. Do upvote our blog to help other ninjas grow. Happy Coding!