The middle expression in a for look, and the expression in a while loop both evaluate to true or false, they both will execute their blocks only if the condition evaluates to true:
Code:
for (int n = 0; n < 5; n++); // Runs 5 times with values of n being {0,4} going in a positive direction.
for (int n = 4; n >= 0; n--); // Runs 5 times with values of n going from 4 to 0.
With while loops a quick way to limit the iterations might be:
Code:
int numTries = 5;
std::string password("");
while (n--)
{
password = promptUserForPassword();
if (validatePassword(password))
{
break;
}
}
Or to really whittle it down:
Code:
int numTries = 5;
while (n--)
{
if (validatePassword(promptUserForPassword()))
{
break;
}
}
You could also selectively inject hints, based on the condition of an incorrect password:
Code:
int numTries = 5;
bool failedAttempt = false;
std::string hint("Hint: My girl!"); // A real world hint! :P
while (n--)
{
if (failedAttempt)
{
std::cout << hint << "\n";
}
// alternate: // std::cout << (failedAttempt ? hint + "\n" : "");
if (validatePassword(promptUserForPassword()))
{
break;
}
// We can only get here if the password is incorrect:
failedAttempt = true;
}