A very simple piece of code for the beginner in C++. It demonstrates how to calculate the average of some numbers. Uses the ‘for’ loop.
// Calculating the average
#include <iostream>
using namespace std;
int main()
{
cout << "Enter how many values you want to add: ";
int items;
cin >> items;
double num;
double sum;
sum = 0.0;
for (int x = 1; x <= items; x++)
{
cout << "#" << x << " = ";
cin >> num;
sum += num; // equal to sum = sum + num
}
cout << "Items = " << items << "\nSum = " << sum << "\nAverage = " << sum / items << "\n";
return 0;
}
cout << "Enter how many values you want to add: ";
We prompt the user to enter the number of values he wants to calculate.
int items;
cin >> items;
Create a variable that stores the number of values that should be calculated and using “cin >>” to enter the input from the user’s keyboard into our new variable. Let’s suppose you wanted 3 values.
double num;
double sum;
sum = 0.0;
The ‘num’ variable will store the numbers the user will input.
We won’t use an ‘int’ because some of the numbers the user will enter will probably be of the ‘double’ type (6.4, 3.2, 145.1).
The ‘sum’ variable will store the sum of all the numbers entered by the user. Also we initialize the variable to ‘0.0’.
for (int x = 1; x <= items; x++)
We start the loop by creating a variable and setting it to the value ‘1’. We check if the variable is smaller than the number of items the user has entered. If it is the loop ends and displays the result. We also want to increment the variable by ‘1’ (x++) every loop.
cout << "#" << x << " = ";
cin >> num;
sum += num; // equal to sum = sum + num
On the first line of the loop, we display the current number the user must enter. If you wanted to calculate 3 numbers you will get:
#1 = <here you enter the number that you want to calculate in the average>
#2 = <here you enter the number that you want to calculate in the average>
#3 = <here you enter the number that you want to calculate in the average>
After you enter all 3 numbers, the loop ends because ‘x <= items’ returns false.
cin >> num;
sum += num; // equal to sum = sum + num
Using “cin >> num;” we store the input from the user’s keyboard in the variable ‘num’.
Then we assign to ‘sum’ the result of the current value stored in sum plus the new value entered by the user.
You should already know that ‘sum += num’ is the short way to write ‘sum = num + sum’.
cout << "Items = " << items << "\nSum = " << sum << "\nAverage = " << sum / items << "\n";
We output the number of items the user choosed to enter, the sum of them and finally we divide the sum of the numbers entered by the user to the number of items.