tries++
is just a shorthand way (of incrementing and assigning) and is equivalent to tries = tries + 1
As an aside, the code in the exercise isn’t quite correct and has a few mistakes. Even though the intent is to limit the user to 3 incorrect attempts, in reality the user can make a maximum of 5 attempts. If we want, a few minor tweaks to the code can fix this anomaly.
If you want to confirm that you are allowed 5 attempts (in the unedited program originally used in the exercise), then enter an incorrect pin e.g. 2019
every single time. You will see that the program ends after the 5th attempt.
A snippet of the original code of the exercise is:
int pin = 0;
int tries = 0;
std::cout << "BANK OF CODECADEMY\n";
std::cout << "Enter your PIN: ";
std::cin >> pin;
while (pin != 1234 && tries <= 3) {
std::cout << "Enter your PIN: ";
std::cin >> pin;
tries++;
}
In this code, we initialize both pin
and tries
to 0
. Then it prompts the user for the pin (FIRST PROMPT) and saves the user’s input into the variable pin
(it doesn’t do anything to tries
which is an oversight by the code author).
If the entered pin is correct, then we skip the loop and go to the end of the program.
Suppose we entered 2019 as our pin, then the condition pin != 1234 && tries <= 3
will be evaluated as 2019 != 1234 && 0 <= 3
which is TRUE, so we will enter the while loop.
In the while loop, we will be prompted for our pin again (suppose we enter 2019 again) (SECOND PROMPT). Then tries++
will change tries
to 1.
At the start of the next iteration of the while loop, the loop condition pin != 1234 && tries <= 3
will be evaluated as 2019 != 1234 && 1 <= 3
which is TRUE, so we will do another iteration of the while loop.
In the while loop, we will be prompted for our pin again (suppose we enter 2019 again) (THIRD PROMPT). Then tries++
will change tries
to 2.
At the start of the next iteration of the while loop, the loop condition pin != 1234 && tries <= 3
will be evaluated as 2019 != 1234 && 2 <= 3
which is TRUE, so we will do another iteration of the while loop.
In the while loop, we will be prompted for our pin again (suppose we enter 2019 again) (FOURTH PROMPT). Then tries++
will change tries
to 3.
At the start of the next iteration of the while loop, the loop condition pin != 1234 && tries <= 3
will be evaluated as 2019 != 1234 && 3 <= 3
which is TRUE, so we will do another iteration of the while loop.
In the while loop, we will be prompted for our pin again (suppose we enter 2019 again) (FIFTH PROMPT). Then tries++
will change tries
to 4.
At the start of the next iteration of the while loop, the loop condition pin != 1234 && tries <= 3
will be evaluated as 2019 != 1234 && 4 <= 3
which is FALSE, so we will exit the while loop.