In: Computer Science
Write a console application to total a set of numbers indicated and provided by a user, using a while loop or a do…while loop according to the user’s menu choice as follows:
C++programming
Menu
1. To total numbers using a while loop
2. To total numbers using a do...while loop
Enter your menu choice: 1
How many numbers do you want to add: 2
Enter a value for number 1: 4
Enter a value for number 2: 5
The total is: 9
Example
Menu
1. To total numbers using a while loop
2. To total numbers using a do...while loop.
Enter your menu choice: 1
How many numbers do you want to add: 4
Enter a value for number 1: 3
Enter a value for number 2: 2
Enter a value for number 3: 5
Enter a value for number 4: 1
The total is: 11
Requirements
Program:
#include <iostream>
using namespace std;
int
main ()
{
int menuChoice, numbersCount;
// Display menu
cout << "Menu" << endl;
cout << "1. To total numbers using a while loop" << endl;
cout << "2. To total numbers using a do...while loop" << endl;
// Take input for menu choice
cout << "Enter menu choice: ";
cin >> menuChoice;
// Take input for how many numbers to be added
cout << "How many numbers do you want to add: ";
cin >> numbersCount;
int arr[numbersCount];
// Take input for numbers and add them to an array
for (int i = 0; i < numbersCount; ++i) {
cout << "Enter a value for number " << i+1 << ": ";
cin >> arr[i];
}
// condition to check the menu choice is 1
if (menuChoice == 1) {
int sum = 0;
int n = 0;
// Sum the numbers using while loop
while(n < numbersCount) {
sum += arr[n];
n++;
}
// Printing the sum of the elements
cout << "The total is: " << sum;
}
// condition to check the menu choice is 2
else if (menuChoice == 2) {
int sum = 0;
int n = 0;
// Sum the numbers using do...while loop
do {
sum += arr[n];
n++;
}
while (n < numbersCount);
// Printing the sum of the elements
cout << "The total is: " << sum;
}
return 0;
}
Output: