Menu Based Program using C++
/*
This challenge is about using a collection (list) of integers and allowing the user
to select options from a menu to perform operations on the list.
Your program should display a menu options to the user as follows:
P - Print numbers
A - Add a number
M - Display mean of the numbers
S - Display the smallest number
L - Display the largest number
Q - Quit
Enter your choice:
*/
#include <iostream>
#include <vector>
using namespace std;
void print(vector<int> &numbers);
void add(vector<int> &numbers);
void display_mean(vector<int> &numbers);
void smallest_value(vector<int> &numbers);
void largest_value(vector<int> &numbers);
int main() {
char selection {};
vector<int> numbers {};
int num_to_add;
do{
// Display menu
cout << "\nP - Print numbers" << endl;
cout << "A - Add a number" << endl;
cout << "M - Display mean of the numbers" << endl;
cout << "S - Display the smallest number" << endl;
cout << "L - Display the largest number"<< endl;
cout << "Q - Quit" << endl;
cout << "\nEnter your choice: ";
cin >> selection;
if (selection == 'P' || selection == 'p') {
print(numbers);
}
else if (selection == 'A' || selection == 'a') {
add(numbers);
}
else if (selection == 'M' || selection == 'm') {
display_mean(numbers);
}
else if (selection == 'S' || selection == 's') {
smallest_value(numbers);
}
else if (selection == 'L' || selection == 'l') {
largest_value(numbers);
}
else if (selection == 'Q' || selection == 'q') {
cout << "Goodbye" << endl;
} else {
cout << "Unknown selection, please try again" << endl;
}
}while(selection != 'q' && selection != 'Q');
cout << endl;
return 0;
}
void print(vector<int> &numbers){
if (numbers.size() == 0)
cout << "[] - the list is empty" << endl;
else {
cout << "[ ";
for (auto num: numbers)
cout << num << " ";
cout << "]" << endl;
}
}
void add(vector<int> &numbers){
int num_to_add;
cout << "Enter an integer to add to the list: ";
cin >> num_to_add;
numbers.push_back(num_to_add);
cout << num_to_add << " added" << endl;
}
void display_mean(vector<int> &numbers){
if (numbers.size() == 0)
cout << "Unable to calculate mean - no data" << endl;
else {
int total {};
for (auto num: numbers)
total += num;
cout << "The mean is : " << static_cast<double>(total)/numbers.size() << endl;
}
}
void smallest_value(vector <int> &numbers){
if (numbers.size() == 0)
cout << "Unable to determine the smallest - list is empty" << endl;
else {
int smallest = numbers.at(0);
for (auto num: numbers)
if (num < smallest)
smallest = num;
cout << "The smallest number is: " << smallest << endl;
}
}
void largest_value(vector<int> &numbers){
if (numbers.size() == 0)
cout << "Unable to determine largest - list is empty"<< endl;
else {
int largest = numbers.at(0);
for (auto num: numbers)
if (num > largest)
largest = num;
cout << "The largest number is: " << largest << endl;
}
}
Comments
Post a Comment