WAP to calculate the sum of all elemets of an array
Objective
Write a C++ program to calculate the sum of all elements in an array.
Algorithm / Approach
- Declare an integer array
a[5]andsum = 0. - Read 5 elements from the user using a
forloop. - Use a second
forloop to iterate through the array. - Add each element to the running total:
sum = sum + a[i]. - Print the sum.
main.cpp
#include<iostream>
using namespace std;
int main() {
int i, a[5],sum = 0;
cout<<"Enter 5 Elements : ";
for(i =0; i< 5; i++) {
cin>>a[i];
}
for(i =0; i< 5; i++) {
sum = sum +a[i];
}
cout<<"Sum = "<< sum<< endl;
return 0;
}
Expected Output
Enter 5 Elements : 12 13 14 15 14 Sum = 68
Explanation of the Program
- An array is a contiguous block of memory that holds multiple variables of the same data type.
- Arrays in C++ are 0-indexed, meaning an array of size 5 has elements at indices 0, 1, 2, 3, and 4. We use loops because the loop counter
imaps perfectly to these indices.
Complexity
Time Complexity
O(n) - Where n is the size of the array.
Space Complexity
O(n)