In: Computer Science
Write a C++ program that checks if the password is correct. The password is a 4-digit number combination. The program repeats to ask the password until the password is correct or you enter -1 to exit.
Input: The password is set to ‘1123’. A user input the password to proceed, or -1 to exit.
Sample Output: The program should display the following output. (The red text is a user input.)
Test case 1: when you enter the correct password.
Enter the password (or -1 to exit): 1234
Password is incorrect.
Enter the password (or -1 to exit): 1123
Password is correct. Test case 2: when you exit the program.
Enter the password (or -1 to exit): -1
You exit the program.
/* C++ program that checks if the password is correct.
The program repeats to ask the password until the password is correct or the user enter -1 to exit. */
#include <iostream>
using namespace std;
int main()
{
int password = 1123; // correct password
int user_password;
// input of user password
cout<<"Enter the password (or -1 to exit): ";
cin>>user_password;
// loop continues till user exits
while(user_password != -1)
{
// check if password is correct, print success message and then exit from loop
if(password == user_password)
{
cout<<"Password is correct"<<endl;
break;
}else // print failure message
cout<<"Password is incorrect."<<endl;
// input of password
cout<<"Enter the password (or -1 to exit): ";
cin>>user_password;
}
// check if user exited the program
if(user_password == -1)
cout<<"You exit the program."<<endl;
return 0;
}
//end of program
Output: