Find The Sum Of All Elements In An Array In C++

Here in this tutorial, we will be learning about how to find the sum of all elements in an array in C++. I am using Turbo C++ version 2.2 to execute the same.

To find the sum of all elements in an array in C++ is an easy task. With some easy methodologies and for loops, sum of the elements can be calculated.

So, let’s get started.

Finding Sum Of Elements In The Array in C++

Let’s see the code of the program first.


void main()
int limit,arr[20];
int sum=0;
cout<<"Enter The Number Of Elements: ";

for(int i=0;i<limit;i++)
cout<<"Enter Element "<<i+1<<": ";
cout<<"The Sum Of The Elements In Array Is: "<<sum;

Now let’s see what every code line means here.

First, as usual, the common header files have been included, that are iostream.h & conio.h. Conio.h header file has been used to clear the screen and hold the output screen for the user to see when the program ends.

Next is our main function, which includes all the codes responsible for conducting the program. Clrscr() function has been used to clear the screen before printing the output to the user, so that the output doesn’t look messy. Otherwise, this function can be omitted.

Then, we have declared 3 things. First, an integer variable named limit, which will be used to define the number of elements in the array according to the user. Then, we have declared an integer type array of size 20. You can take up any size you want. Then we have declared another integer variable named sum, having value 0 in beginning. It will be storing the value of the sum of the elements of the array. Then, we have asked the user to enter the total number of elements in the array.

Now we will move on to for loop.

For Loop

For loop has been used here to enter the elements in the array¬†ONE by ONE.¬†First, we have initialized a counter variable i, which will be taking up array values from the user, till it reaches the limit defined by the user. The value of i will be iterated by 1 in every loop conduct, hence it’s written i++.

Then, the user will be entering the elements in the array one by one and in the same loop, the values will be one by one added in the variable sum. Like, if the first value is entered 2, sum will have value 2. Then if the next value is 3, sum will have value 5, as it keeps on adding the array elements in the variable sum. In this way, we will be able to find out the sum of all elements in the array easily.

Then, we have printed the desired results, which is the sum of all elements in the array to the user.

getch() function has been used to hold the output screen to the user before closing the program.


Enter The Number Of Elements: 5

Enter Element 1: 1

Enter Element 2: 2

Enter Element 3: 3

Enter Element 4: 4

Enter Element 5: 5

The Sum Of The Elements In Array Is: 15

Learn more:

Leave a Reply

Your email address will not be published. Required fields are marked *