Calculating Averages with Ease in C++
Setting the Stage
To calculate the average of a set of numbers, we’ll define an array num
to store up to 100 floating-point numbers. We’ll also ask the user to specify how many numbers they want to calculate, storing this value in the variable n
. However, n
needs to be between 1 and 100. If the user enters an invalid value, we’ll use a while
loop to prompt them to try again.
int n;
while (true) {
cout << "Enter the number of values (between 1 and 100): ";
cin >> n;
if (n >= 1 && n <= 100) {
break;
}
cout << "Invalid input. Please try again." << endl;
}
Gathering Input
Once we have a valid n
, we can use a for
loop to input the numbers from the user and store them in the num
array. With each number entered, we’ll add its value to the sum
variable. By the end of the loop, sum
will hold the total sum of all the numbers.
float num[100], sum = 0;
for (int i = 0; i < n; i++) {
cout << "Enter value " << (i + 1) << ": ";
cin >> num[i];
sum += num[i];
}
Calculating the Average
Now it’s time to calculate the average. We’ll divide the sum
by n
to get the final result, which we’ll display to the user.
float average = sum / n;
cout << "The average is: " << average << endl;
Taking it Further
Want to explore more C++ programming topics? Check out our program to find the largest element of an array, which showcases another essential skill in C++ development. With practice and patience, you’ll be unlocking the full potential of C++ in no time!
- Mastering arrays and loops is crucial in C++ development.
- Practice calculating averages and finding the largest element in an array to improve your skills.
- Experiment with different scenarios to solidify your understanding of C++ concepts.