Write a program in C++ coding that asks the user to input an integer between 25 and 50, inclusive.
Utilize a WHILE loop to test for INVALID input. If the input is INVALID, the loop will repeat, and ask the user to try again.
The pseudocode looks like this:
Prompt user to input an integer between 25 and 50
Accept the input from the user
Test for invalid input (HINT: use a while loop and the OR operator with 2 relational expressions. You are testing if the number is less than 25 OR greater than 50, because you are testing for INVALID input to repeat the body of the loop)
{
display a user-friendly message to try again
accept the input from the user
}
Display a user-friendly message echoing the valid input.
Validate your code by running it with valid input and invalid input.
Cpp Code:
#include <iostream>
using namespace std;
int main()
{
int num;
//getting the number from the user
cout << "Input an integer between 25 and 50: " <<
endl;
cin >> num;
//looping until user enters number between 25 and 50
while(num<25 || num>50){
//error message
cout<<"INVALID...try again"<<endl;
cin >> num;
}
//valid input
cout<<"Valid Input is: "<<num;
return 0;
}
Sample Output:
Input an integer between 25 and 50:
60
INVALID...try again
24
INVALID...try again
25
Valid Input is: 25
Get Answers For Free
Most questions answered within 1 hours.