Introduction
In this lab, we will learn how to calculate the average of n numbers entered by the user without making use of an array in C++. We will go through the code line by line and understand how it works.
In this lab, we will learn how to calculate the average of n numbers entered by the user without making use of an array in C++. We will go through the code line by line and understand how it works.
We will create a new file named main.cpp
in the ~/project
directory using the following command:
touch ~/project/main.cpp
In the first step, we will include the necessary libraries and use the standard namespace.
#include <iostream>
using namespace std;
In the next step, we will print a welcome message to the user and declare the variables used in the program.
int main()
{
cout << "\n\nWelcome to the Average Calculator!\n\n";
int n, i, temp;
double sum = 0, average = 0;
}
We declare the following variables:
n
is the number of integers entered by the user.i
is a loop variable.temp
is a temporary variable to read the user input.sum
holds the sum of all the values entered by the user.average
calculated as the sum divided by n.In the next step, we will read the input from the user. We will prompt the user for the number of integers they want to find the average of.
cout << "Enter the number of integers: ";
cin >> n;
Then, we will ask the user to enter each number one by one. We will use a for loop to get the user input and add the entered number to sum.
for (i = 1; i <= n; i++)
{
cout << "Enter number " << i << ": ";
cin >> temp;
sum += temp;
}
We can now calculate the average of the entered numbers using the sum and the number of integers.
average = sum / n;
The last step is to output the final result to the user.
cout << "\n\nThe Sum of the " << n << " numbers entered by the user is: " << sum << endl;
cout << "\nThe Average of the " << n << " numbers entered by the user is : " << average << "\n\n";
#include <iostream>
using namespace std;
int main()
{
cout << "\n\nWelcome to the Average Calculator!\n\n";
int n, i, temp;
double sum = 0, average = 0;
cout << "Enter the number of integers: ";
cin >> n;
for (i = 1; i <= n; i++)
{
cout << "Enter number " << i << ": ";
cin >> temp;
sum += temp;
}
average = sum / n;
cout << "\n\nThe Sum of the " << n << " numbers entered by the user is: " << sum << endl;
cout << "\nThe Average of the " << n << " numbers entered by the user is : " << average << "\n\n";
return 0;
}
To compile and run the code issue the following commands on the terminal:
g++ main.cpp -o main
./main
In this lab, we learned how to calculate the average of n numbers entered by the user without using an array. We used a for loop to read the input from the user and calculated the sum and average of the entered numbers. Finally, we output the result to the user.