Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to calculate the sum of all elemets of an array

C++ Code Example — Array Programs

ADVERTISEMENT

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

  1. Declare an integer array a[5] and sum = 0.
  2. Read 5 elements from the user using a for loop.
  3. Use a second for loop to iterate through the array.
  4. Add each element to the running total: sum = sum + a[i].
  5. 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 i maps perfectly to these indices.

Complexity

Time Complexity O(n) - Where n is the size of the array.
Space Complexity O(n)
ADVERTISEMENT