codescracker
c++

C++ Program to Find and Print Sum of Array Elements



« C++ Tutorial C++ Example »

This article provides a program in C++ to find and print the sum of all elements available in an array. Here the elements of array must be entered by user at run-time.

Find Sum of All Elements of an Array

The question is, write a program in C++ that find and print the sum of all elements/numbers in a given array. Following program is its answer:

#include<iostream>

using namespace std;
int main()
{
   int arr[10], i, sum=0;
   cout<<"Enter 10 Array Elements: ";
   for(i=0; i<10; i++)
      cin>>arr[i];
   for(i=0; i<10; i++)
      sum = sum+arr[i];
   cout<<"\nSum of all array elements = "<<sum;
   cout<<endl;
   return 0;
}

Here is the initial output produced by above C++ program on finding the sum of all elements of an array entered by user:

c++ program find sum of array elements

Now enter any ten numbers one by one, and press ENTER key to find and print the sum of all elements like shown in the snapshot given below:

find sum of array elements c++

Since there is a limitation of above program. That is, user is only allowed to enter the 10 elements. Therefore let's modify this program and create another program that allows user to define the size of array along with its elements:

#include<iostream>

using namespace std;
int main()
{
   int tot, arr[100], i, sum=0;
   cout<<"Enter the Size for Array (max.100): ";
   cin>>tot;
   cout<<"Enter "<<tot<<" Array Elements: ";
   for(i=0; i<tot; i++)
   {
      cin>>arr[i];
      sum = sum+arr[i];
   }
   cout<<"\nSum of all array elements = "<<sum;
   cout<<endl;
   return 0;
}

Here is its sample run with user input, 6 as size, and 10, 20, 30, 40, 50, 60 as six array elements:

print sum of array elements c++ program

C++ Online Test


« C++ Tutorial C++ Example »



© Copyright 2021. All Rights Reserved.

CodesCracker