# add array elements total in C++

Before starting the Program of add array elements Total in C++ you clear your array in C++ concept.

Here we will calculate sum of all elements available in the array using for loop. In this program, we will input some numbers from the user and print their total. In the program, we have declared three variables.

``int arr[10],num,sum=0;``

In which the variable sum has been initialized. Here, we have given 10 the size of the array arr. Which means that we can only store maximum 10 elements in an array-variable arr[] at a time.

``````#include<iostream>
using namespace std;

int main()
{
int arr[10],num,sum=0;

cout<<"how much element you want to enter: \n";
cin>>num;

cout<<"Enter "<<num<<" Element: ";

for(int i=0;i<num;i++)
cin>>a[i]; // store values in variable a[]

for(int j=0; j<n;j++)
{
cout<<a[j]<<" ";     // print array element
sum=sum+a[j];      // sum of array element
}

//Print sum of array element
cout<<"\nTotal of These Element are: "<<sum;

return 0;
}``````

OUTPUT

`how much element you want to enter:: 6 Enter 6 Element: 4 8 9 1 4 2 Your element is: 4 8 9 1 4 2 Total of These Element are : 28`

explanation Suppose the user has given an array size 6,

``num = 6``

And the 6 elements were stored in this way,

``````arr[0] = 4
arr[1] = 8
arr[2] = 9
arr[3] = 1
arr[4] = 4
arr[5] = 2``````

now loop will start from here, 1st j = 0 n = 6

``````for(int j = 0; 0 < 6; 0++)
{
cout<<4<<" ";
sum=0+4;
}``````

2nd j = 1, num = 6, sum = 4

``````for(int j=1; 1 < 6; 1++)
{
cout<<8<<" ";
sum=4+8;
}``````

3rd j = 2, num = 6, sum=12

``````for(int j=2; 2 < 6; 2++)
{
cout<<9<<" ";
sum=12+9;
}``````

4th j = 3, num = 6, sum = 21

``````for(int j=3; 3 < 6; 3++)
{
cout<<1<<" ";
sum=21+1;
}``````

5th j = 4 num = 6, sum = 22

``````for(int j=4; 4 < 6; 4++)
{
cout<<4<<" ";
sum=22+4;
}``````

6th j = 5, num = 6, sum = 26

``````for(int j=5; 5 < 6; 5++)
{
cout<<2<<" ";
sum=26+2;
}``````

7th j = 6, num = 6, sum = 28

``````for(int j=6; 6 < 6; 5++)
{
skip
}``````

In 7th execution condition becoming false 6<6 so here loop will be terminate and outside the loop will next statement execute, outside the loop variable sum value will be print which is now 28. so thus program will execute successfully. see also: Add Elements of Two Different Array using single dimensional and multidimensional array.

Related exercise,

C++ Examples

Like it?