194k views
0 votes
Using a counter and an if statement inside the while loop, only allow the user five opportunities before ending the program. If the user gets to 5 incorrect inputs, display a message that they have hit the limit of tries and exit the program. (HINT: To completely stop a program use the return command.)

1 Answer

7 votes

Answer:

#include <iostream>

using namespace std;

int main ()

{ int cutoff = 5;

int tries = 0;

int u_input = 0;

while (0 == 0)

{ if (tries == cutoff)

{

cout << "You have hit the limit of tries ";

return 0;}

else {

cout << "Enter a postive number";

cin >> u_input;

if (u_input < 0)

{

tries++;

cout << "Not a postive number, Try again !";

}

}

}

return 0;

}

Step-by-step explanation:

create a variable cutoff of type integer for maximum allowed user inputs.

create a variable tries of type integer for number of user inputs.

create a variable u_input of type integer for user inputs.

create an infinite while loop with termination condition 0==0. Inside loop write an if statement where if tries==cutoff return 0 (to terminate program) else ask proceed to ask user for a positive integer number as input.After input check if input number is positive.If input number is positive terminate else increase tries variable value by one ask user to input again

User Jonba
by
5.3k points