Help with switching (if else loop) to (while loop) C++

closed account (ozh0oG1T)
Prompt: Write a while loop that ask the user to enter their pin. If the user enters the wrong pin tell the user they entered the incorrect pin. Give the user 3 tries until before telling the user they are out of attempts. Test out your program by entering incorrect pins then the correct pin. The correct user pin in 4213.

SN: My program runs fine with the if else loop but I need help trying to work it for a while loop.

#include <iostream>
using namespace std;

int main()
{
int attempts = 0;
string pin;

for ( attempts = 0; attempts < 5; ++attempts )
{
cout << "Enter Your Pin: ";
cin >> pin;
++attempts;

if ( pin == "4213" )
{
cout << "Correct Pin ";
return 0;
}
else
{
cout << "You are out of attempts ";
}
}

return 0;
}
Last edited on
for loops and while loops are semantically very similar.

But if/else are NOT loops, so it makes no sense to try and replace them with a loop construct.

> for ( attempts = 0; attempts < 5; ++attempts )
Your assignment said 3, not 5.

> ++attempts;
Yeah, counting twice (or not) each time will drive you nuts.
Topic archived. No new replies allowed.