KIM
KIM

Reputation: 47

How to count iteration on a loop

I am teaching myself looping in C and I wanted to know how can the user try the password only 3 times?

When the first time is correct it returns correct,my current loop doesn't do the intended.

int password = 8795, guessed = 3;

while(1) {

    printf("\n\n");
    printf("Please Enter Your Password");
    scanf ("%d ", &guessed);

    if (guessed == password ) {
        printf("Correct Password");
    } else if(guessed != password) {
        printf("Please try again for the second time");
    } else {
        printf("Please try again for the last time");
        break;
    }
}

Upvotes: 0

Views: 152

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 311038

I think you mean the following

int password = 8795, guessed;
int attempts = 3;
int valid = 0;

printf("\n\n");
printf("Please Enter Your Password");
do
{
    scanf ("%d ", &guessed);
    --attempts;

    if ( valid = guessed == password )
    {
        printf("Correct Password");
    }
    else if( attempts != 1 )
    {
        printf("Please try again for the second time");
    }
    else
    {
        printf("Please try again for the last time");
    }
} while ( !valid && attempts != 0 );

Upvotes: 2

Henrik Carlqvist
Henrik Carlqvist

Reputation: 1168

Instead of initializing guessed to 3 I would add a new variable, maybe called attempts_left and initialize that to 4. Your guessed variable gets overwritten from the users input.

Your if, else, else will never get to the last else. Your first else does not need any if condition as its current condition is the inverse of the condition at the if row.

Instead of having while(1) you might want to have something like while(--attempts_left>0). You probably do not want to have any break in the last else, instead you probably want to break the while loop when the password is right. Outside the while loop you might want to check if the while loop ended because the password was right or because the user ran out of retries.

Upvotes: 0

Linuxios
Linuxios

Reputation: 35803

To loop n times in C, use a for loop:

for(int i = 0; i < n; i++) {
  /* loop contents */
}

In this case, replace n with 3. In your case, however, it makes more sense while reading the code to do as @Michiel Uit Het Broek suggested and use a while loop:

int guessesLeft = 3;
while(guessesLeft > 0) {
  /* loop contents */
  guessesLeft--;
}

To exit the loop with the password is correct, use break:

if(guessed == password) {
  break;
}

Upvotes: 3

Related Questions