简体   繁体   中英

Why does my while loop allow the wrong amout of tries

Im just learning c++ and have this program I'm wondering why when I run the program through terminal it allows 5 trys when I set tries <= 3 and if I change it to tries <= 1 it allows the correct amount of tries

#include <iostream>

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

    else{
      cout << "incorrect please try again later";
  }
  
}

You have a cin >> pin before the loop and a cin >> pin inside the loop that gets executed 4 times ( tries from 0 to 3 inclusive). Total 5 times you ask for input.

You start loop counter from zero. So it has 4 iterations:

  1. 0 <= 3 = true
  2. 1 <= 3 = true
  3. 2 <= 3 = true
  4. 3 <= 3 = true

Loop will break on 5-th iteration because condition would fail (4 <= 3 = false). So you have to change condition from <= to < and it'll work correct or start counting tries from 1.

Also you left pins' input before loop and it causes additional iteration. You can remove that unnecessary iteration and use do... while loop instead:

do {
  cout << "Enter your PIN: ";
  cin >> pin;
  tries++;
} while (pin != 1234 && tries <= 3);

But if you'll use do... while loop, you should use <= as an loop condition because your iteration count will be 2.

Also I left some visual explanation below. Hope it'll help.

Explanation on image

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM