IDunnoHowTOCode
IDunnoHowTOCode

Reputation: 13

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";
  }
  
}

Upvotes: 0

Views: 56

Answers (2)

Daniel Bibik
Daniel Bibik

Reputation: 51

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

Upvotes: 2

bolov
bolov

Reputation: 75853

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.

Upvotes: 3

Related Questions