Simple Array Sum
In this post we will be covering Simple Array Sum, in which we have to calculate the total sum of all the elements present in an array. The size and elements of the array is user inputted hence can vary upon different sets of inputted values. The solution is carried out in C++ with the required sets of variables, initializations, looping and output to get.
Given an array of integers, find the sum of its elements.
For example, if the array = [1, 2, 3], 1 + 2 + 3 = 6, so return 6.
Complete the function in the editor below. It must return the sum of the array elements as an integer.
simpleArraySum has the following parameter(s):
: an array of integers
The first line contains an integer, n, denoting the size of the array.
The second line contains n space-separated integers representing the array's elements.
Print the sum of the array's elements as a single integer.
We print the sum of the array's elements: 1 +2 +3 + 4 +10 + 11 = 31.
🔍Logic to follow to come-up with the solution :
1. Declare the required sets of variables to use.
2. Initialize the sum variable to zero, at last it will hold the summation value of the elements that are present in the array.
3. Take the required sets of input from the user.
4. Apply the looping(here applying a for loop) to repeatedly add the elements inside the array.
i.e., from initializing to 0 till the number of elements present in the array
for( int i=0 ;i<n ;i++) let sum=sum+ar[i];
5. For loop will encounter until the condition fails.
6. Finally the sum variable holds the resulted value of added elements.
7. At last the sum variable is printed out of the loop.
👨💻Let’s write the required code for the problem :
Sample Test Cases have been passed successfully
If you liked this post, then share this with your friends and if anything is confusing or incorrect then let me know in the comment section.
Thanks from my side, this is Mayank, keep learning and exploring !!