C++ Program to find Sum of Elements in an Array

Sum of Elements in an Array

Today we will learn how to find sum of elements in an array is easy task when you know how to iterate through array elements. In this problem we will explain you C++ approach to find sum of array elements inputted by the user.
Here is the solution of this query in C++ Language.

C++ program to find largest element

Working:-

  1. Input the size of array and store the value in m and arr[m].
  2. To store sum of array elements, initialize a variable sum = 0.
  3. To find sum of all elements, iterate through each element and add the current element to the sum.
  4. Inside the loop add the current array element to sum i.e.sum = sum + arr[i] or sum += arr[i].

C++ Program:-

#include <iostream>
using namespace std;
#define ARR_SIZE 100
int main()
    {
        int arr[ARR_SIZE];
        int i,m,size,sum=0;
        cout<<"Enter size of the array:";// Input size of the array
        cin>>m;
    
        cout<<"Enter %d elements in the array: ";// Input elements in array
        for(i=0; i<m; i++)
        {
            cin>>arr[i];
        }
        for(i=0; i<m; i++)  //Add each elements to sum array
         {
            sum = sum + arr[i];
         }
        cout<<"Sum of elements in an array = "<<sum;
        return 0;
    }
Output:
Enter size of the array: 5
Enter 5 elements in the array: 5
5
5
5
5
Sum of elements in an array = 25