111k views
3 votes
Write a C++ program that loops forever and asks the user to enter 5 positive numbers in the close range [1, 100], and then print out to screen the average and median values. Check for invalid values for the five integers and continue to beginning of the loop if any value is invalid. Write two functions and use them in the program: double find_average(..) size_t find_median(..) Use array of 5 elements of type size_t or n1, n2, n3, n4, n5 as inputs to the functions. Ask the user if they want to repeat at the end of the while loop.

User Benjin
by
8.7k points

1 Answer

3 votes

Final answer:

The student's requirement is to develop a looping C++ program that asks for five positive numbers in the specified range, computes average and median using two defined functions, and manages invalid inputs with user interaction to repeat the process.

Step-by-step explanation:

The C++ program requested will loop indefinitely, prompting the user to enter five positive numbers within the range [1, 100]. It will then calculate and print the average and median of these numbers using the functions find_average and find_median. If any input is invalid, the program will continue to the beginning of the loop. The user will be asked if they wish to repeat the process at the end of each iteration.


#include <iostream>
#include <algorithm>
using namespace std;

double find_average(size_t arr[]) {
double sum = 0;
for (int i = 0; i < 5; i++) {
sum += arr[i];
}
return sum / 5;
}

size_t find_median(size_t arr[]) {
sort(arr, arr + 5);
return arr[2]; // The middle element for 5 numbers
}

int main() {
while (true) {
size_t numbers[5];
for (int i = 0; i < 5; i++) {
cout << "Enter a positive number (1 to 100): ";
cin >> numbers[i];
if (numbers[i] < 1 || numbers[i] > 100) {
cout << "Invalid value. Try again." << endl;
continue;
}
}

double avg = find_average(numbers);
size_t median = find_median(numbers);

cout << "Average: " << avg << endl;
cout << "Median: " << median << endl;

char repeat;
cout << "Do you want to repeat? (y/n): ";
cin >> repeat;
if (repeat != 'y' && repeat != 'Y') break;
}
return 0;
}

User Hugo Matilla
by
8.1k points

No related questions found