C++ tutorial- Arrays: sum all elements of an array of integers

C++ code to sum all elements of an array of integers

In this page, we provide one more C++ code example that sums all elements of an integral array and their average value is also calculated.

To sum all elements of an array you need to use a loop to traverse through the array(using every index). Each element of the array will be cumulated and stored in to a variable. For the C++ code example below, we allow a user to input a number of his/her data points then the program will display the total and average of the data set.

Example: C++ code to sum all elements of the array

#include <cstdlib>
#include <iostream>
#include <conio.h>

using namespace std;

void sumArray(){
  int sum=0,n;
  float avg=0;
  cout<<"Enter number of items in the data set:";
  int dset[n];
  int i;
  for(i=0;i<n;i++) { //input array elements
  //sum elements of the array and calculate the average


//Start main
int main(){
  return 0;


//End main


Troy comment


for more C++, C exercises,
please visit http://ccphplusplus.blogspot.com/


This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.