FAQ: Loops - While Loop Demo

This community-built FAQ covers the “While Loop Demo” exercise from the lesson “Loops”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Learn C++

FAQs on the exercise While Loop Demo

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

The first statements for asking the pin can be removed as they are stated in the exact way in the while loop. Makes for shorter code!

here in the while loop condition is given that try <= 3,means it will take upto 3 values . more than 3 values it will break. but after executing the program, it is taking upto 5 values . why?

3 Likes

I had this same question! I see this was posted in July 2019, and no response to it yet.

So I’ll give it a try, as my first response to any question on Codecademy.

Specifically, the question is: Why does the code on line 13 in the exercise:

while (pin != 1234 && tries <= 3)

continue to allow entries after three tries? Specifically, it allows five tries! Which is odd, because “tries <= 3” implies that the loop will stop after 3 tries.

What I see is two things going on here:

  1. The variable “tries” was initialised to 0 on line 6. This means that the computer starts counting from zero on line 17 (code: “tries++;”). So that gets us to four possible entries (unless you enter the correct pin code, of course).

  2. amonsoares above makes a good point, and this is part of the solution to this question. It’s unclear why lines 10 and 11 are included in the solution code. The two lines call for the pin and allow it to be entered with std::cout and std::cin, but they don’t increment the variable “tries”. So this code runs once. The program then runs through the “while” loop beginning on line 13, which allows the code to be run an additional four times (see point number 1 just above).

  3. Solution: To clean up the code and make it run (more or less) correctly, you have to do two things:

A. Delete lines 10 and 11, as they are completely redundant.
B. On line 6, set “tries” to 1 instead of 0: “int tries = 1;” OR B. On line 13 in the while loop, write the end of the parenthetical as “&& tries < 3”.

Just as a note, I’ve gone through the enter Loops section and at no point is this explained as an example of a coding error. It would, however, make an excellent addition to the section on Bugs (as a logical bug not detectable by the compiler).

Hope this was helpful! Have a good coding day, everyone.

4 Likes

Hello everyone,

I was doing the While Loop Demo today and found a small bug in the exercise.
Instead of generating the default executable a.out using: g++ enter_pin.cpp, I generated an executable with a chosen name: g++ -o main.exe enter_pin.cpp.
When doing this and executing, codecademy does not recognize you finished the exercise, and therefore does not allow you to continue to the next exercise.

1 Like

/* The following comments explain why you have up to 5 tries,
even though it seems like there should only be 3.
Copy and paste into the code editor for markup*/

#include

int main() {
int pin = 0;
int tries = 0;
std::cout << “BANK OF CODECADEMY\n”;
std::cout << "Enter your PIN: ";
std::cin >> pin; //pinenters=1
while (pin != 1234 && tries <= 3) {
std::cout << "Enter your PIN: ";
std::cin >> pin;
tries++;
//pinenters=2, tries=1
//pinenters=3, tries=2
//pinenters=4, tries=3
//pinenters=5, tries=4 (this finally exits the loop)
}

//the code gets here if either (or both) of the following conditions is satisfied:
//case 1. pin is correct
//case 2. pinenters=5, tries=4

//the following code then ensures that it must be case 1 to print the message.
if (pin == 1234) {
std::cout << “PIN accepted!\n”;
std::cout << “You now have access.\n”;
}

//hope this helped to clarify any doubts! :slight_smile:
}

1 Like

Hi,

I’ve compiled the unmodified enter_pin.cpp.
When runing a.out, if I enter a letter (eg. “a”) for the pin, code inside the while loop gets executed four times.
To test what is happening, I put a line inside while loop.
After std::cin >> pin; I’ve put this line:
std::cout << "Entered is: " << pin << std::endl;
Output of this line, i case that letter was input for the pin is value of the pin and this is 0.

Please, can you explain why is it 0?
Why the loop is executed, four time?

Thank you.

Need to copy/paste your code here to get help with such questions.

Hi!

The correct code :
#include

int main() {

int pin = 0;
int tries = 1;

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++;

}

if (pin == 1234) {

std::cout << "PIN accepted!\n";
std::cout << "You now have access.\n"; 

}

}

The mistake , the variable “tries” has been initailizaited by value “0” but should be by value 1 .

2 changes made to this code so that it functions properly

  1. The following lines:

    std::cout << "Enter your PIN: ";
    std::cin >> pin;

are removed from after

std::cout << “BANK OF CODECADEMY\n”;

This prevents the program from asking the user to enter the pin in two instances of the code.

  1. the line:

while (pin != 1234 && tries <= 2) {

replaces

while (pin != 1234 && tries <= 3) {

This is done as tries is initialised with the value 0. This means that try “0” is counted as the first attempt to enter the pin. If we increment this by 1 for each attempt, then try “2” counts as the third attempt.

This issue can also be fixed if

while (pin != 1234 && tries < 3) {

is used.

Feel free to try my version for yourself.


#include

int main() {

int pin = 0;
int tries = 0;

std::cout << “BANK OF CODECADEMY\n”;

while (pin != 1234 && tries <= 2) {

std::cout << "Enter your PIN: ";
std::cin >> pin;
tries++;

}

if (pin == 1234) {

std::cout << "PIN accepted!\n";
std::cout << "You now have access.\n"; 

}

}


Two notes on how to improve this code for the future:

  1. The PIN should be checked if it is 4 digits long. an IF statement using boolean logic can achieve this.

  2. The user should be notified that they entered an incorrect pin value rather than just asking them to re-enter the PIN.

The example still runs 5 times before you compile it, even though it should run 3 times. Fix your code, codecademy!

What purpose does the tries++; lines apply to this code? I’ve been looking at it and trying to understand each lines purpose and played with different lines to see how/if they would break it.

Unlike the others who have stated they get between 4-5 attempts with the initial code supplied, I only get 3 attempts, even with the same code thats explained to give up to 5 attempts.

I couldn’t tell if the tries++ on lines 13 and 19 actually supplied the attempt or not, since line 15 has “while (pin != 1234 && tries < 3)”.

My current understanding of x++ is that it provides an increment to the value listed. But these lines don’t appear to do so.

To see how they worked, I removed lines 13 and 19, compiled, and ran the code again. And nothing changed.

I also tried adding std::cout << tries << “\n”; to the code and have it show the value of tries after each attempt. It seems to ignore the first pin entry and skip to two if the code is placed below the While statement. But if I put it at the top it of course only shows the default value since its before the first pin attempt.

#include <iostream> int main() { int pin = 0; int tries = 0; std::cout << "BANK OF CODECADEMY\n"; std::cout << "Enter your PIN: "; std::cin >> pin; tries++; while (pin != 1234 && tries < 3) { std::cout << "Enter your PIN: "; std::cin >> pin; tries++; std::cout << tries << "\n"; } if (pin == 1234) { std::cout << "PIN accepted!\n"; std::cout << "You now have access.\n"; } }

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.

1 Like

Why is it that the while loop doesn’t terminate after the fourth prompt when 3 <= 3? Shouldn’t the broken code still only reach four attempts instead of five? And how come the tries++ don’t reduce the number of attempts, if they add to the value of tries?

Edit: Ok looking at it again and breaking the code down I think I understand it more, but I still hold my questions I just asked.

I can see that as the while loop runs, the tries++ adds to the value of tries, which is why it allows the while loop to terminate. Otherwise it would simply run on forever, since nothing would be adding to value of tries.

But wouldn’t the first tries++ before the while loop add to the value of tries, causing it to be 1 before the start of the while loop? Which in turn should only allow 2 attempts of the while loops since it would then be 3 <= 3.

Edit 2: Ok while writing this I just realized that the code is still wonky because of the initial request for a pin before the while loop, and it threw me off.

The first tries++ increases the value to 1, and then the subsequent attempts work within the while loop. Which only technically gives us two attempts because of previous said code. It does not need the first pin request at all. But it doesn’t technically break the program from executing how it is intended.

See there is no mistake in the code
Let me tell how it works

1 #include
2
3 int main()
4 {
5 int pin = 0;
6 int tries = 0;
7 std::cout << “BANK OF CODECADEMY\n”;
8 std::cout << "Enter your PIN: ";
9 std::cin >> pin;
10
11 tries++;
12
13 while (pin != 1234 && tries < 3)
14 {
15 std::cout << "Enter your PIN: ";
16 std::cin >> pin;
17 tries++;
18 }
19 if (pin == 1234)
20 {
21 std::cout << “PIN accepted!\n”;
22 std::cout << “You now have access.\n”;
23 }
24 }

/* In line 6 tries is initialized to the value of tries is 0
Line 8 prints on the terminal “Enter the pin:” and Line 9 takes the pin from the user so the user has entered the pin for one time If correct pin(1234) is entered then from line 19 the code gets executed and the program exits
but if wrong pin is entered we proceed below
Line 11 increments the value of tries by 1 making the value of tries 1
Now in Line 13 the while loop starts executing and it checks whether the pin is 1234 or not and value of tries is less than 3 or not.For now the current value of tries is 1 so Line 15 gets executed and prints “Enter the pin:” on the terminal subsequently line 16 gets executed and takes the pin from the user again so the user has entered pin for the second time till now. If correct pin(1234) is entered then from line 19 the code gets executed and the program exits
but if wrong pin is entered we proceed to Line 17 where the value of tries is incremented by 1 making the value of tries 2
Now the while loop checks again if tries is still lesser than 3 and yes it is the current value of tries is 2 so the loop iterates or repeats again where line 15 gets executed and prints “Enter the pin:” on the terminal subsequently line 16 gets executed and takes the pin from the user again so the user has entered pin for the third time till now. If correct pin(1234) is entered then from line 19 the code gets executed and the program exits
but if wrong pin is entered we proceed to Line 17 where the value of tries is incremented by 1 making the value of tries 3
Now the while loop checks again if tries is still lesser than 3 and it is not the current value of tries is equal to 3 contradicting the condition of the loop which wants it to be less than 3 so the loop does’nt iterate or repeat and the program exits
So the user enters the pin for 3 times

Because 3 is equal to 3 so 3 <= 3 is true and it gets in hope it helped