Calculate Average of Numbers in Arrays using C++

Tutorials PanelPosted by

The sample code below is to demonstrate how to calculate the average of integer numbers in an array using C++. It’s a console application that takes the ā€˜nā€™ as an argument, which is the number of element to be stored in an array, then calculates the average of those numbers.

How does this program work?

To make this code simple, the user will only be able to enter 10 numbers to the stored in the array. Remember, n is total of number to be entered, so n can’t be greater than 10. To make that happen, we need to use a loop which will check in n is less than or equal 10. Once a number between 1 and 10 is entered, the program will ask the user to enter the numbers to be stored in the array. One the user enters all the number (n), the program will return the average of all numbers in the array.

#include "stdafx.h"
#include <iostream> 

using namespace std;
int main()
	int n, i;
	float num[10], sum = 0.0, average;
	cout << "Enter how many numbers to calculate:";
	cin >> n; while (n > 10 || n <= 0) {
		cout << "Please enter a number between 1 and 10" << endl;
		cout << "Please enter the number again:";
		cin >> n;
	for (i = 0; i < n; ++i)
		cout << i + 1 << ". Enter number: ";
		cin >> num[i]; sum += num[i];
	} average = sum / n;
	cout << "The average of the numbers you entered: " << average; 
	return 0;

The output is:

Enter how many numbers to calculate:3
1. Enter number: 5
2. Enter number: 42
3. Enter number: 7
The average of the numbers you entered: 18 
Press any key to continue . . .


Related Articles:

Leave a Reply