Problem Instructions Write a program that allows a user to input up to 20 intege
ID: 3631145 • Letter: P
Question
Problem InstructionsWrite a program that allows a user to input up to 20 integers. First ask the user how many numbers (num), up to 20, they wish to enter. Then prompt the user for num numbers, storing them in an array. Finally print the numbers in reverse, separated by a comma and a single space, on a single line.
You should declare an array:
int numbers[20];
but use num to keep track of how many valid entries you have.
Constraints
Do not output a comma after the last number. The output sentence should be same as the example.
If the user enters an invalid number of entries, prompt them to try again.
Examples:
How many numbers will you be entering (up to 20): 5
Enter a number: 3
Enter a number: 5
Enter a number: 8
Enter a number: 300
Enter a number: 12
Numbers in reverse: 12, 300, 8, 5, 3
How many numbers will you be entering (up to 20): 50
Try again (valid numbers are 1-20): 5
Enter a number: 3
Enter a number: 5
Enter a number: 8
Enter a number: 300
Enter a number: 12
Numbers in reverse: 12, 300, 8, 5, 3
Explanation / Answer
#include <iostream>
using namespace std;
int main()
{
//LOCAL DECLARATIONS
int numbers[20];
int num;
//PROCEDURES
cout << "How many numbers will you be entering (up to 20): ";
cin >> num;
cin.ignore();
while (num > 20 || num < 1)
{
cout << "Try again (valid numbers are 1-20): ";
cin >> num;
cin.ignore();
}
for (int i = 0; i < num; i++)
{
cout << "Enter a number: ";
cin >> numbers[i];
cin.ignore();
}
cout << "Numbers in reverse: ";
cout << numbers[num - 1]; //display last element
for (int i = num - 2; i > -1; i--)
{
cout << ", ";
cout << numbers[i];
}
cout << endl;
cin.get();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.