I have been learning to code for a few days and today I decided to use my limited capabilities to try to code this. I am trying to make a loop for a password input where if the password entered is correct, the loop will end. And if password is incorrect it will give you two more tries to input it correctly. I have tried writing a while loop like shown below. However, this not only did not fix the problem it also ruined the previous somewhat functional loop. Now it just accepts any input forever without giving anything back.
If you have any fixes and tips please share them!
Many thanks!
#include <stdio.h>
#include <cs50.h>
int main(void)
{
long password;
int ask;
int tries = 0;
int keepgoing = true;
ask = get_int("Enter Password: ");
password = 123456789;
while (tries < 3 && keepgoing == true);
if (ask == password)
{
printf("Correct!!!\n");
keepgoing = false;
}
if (ask != password)
{
printf("Incorrect, Try Again!!!\n");
}
if (tries == 3)
{
printf("Too many wrong attempts\n");
keepgoing = false;
}
}
>Solution :
A little thing you forgot is "else if". By adding this, you code will loop through each of the condition as if they were a whole. Therefore, your code will stop running when a condition is met. Also, your final if statement is useless as you while loop will expire once tries = 3. Another little thing you forgot is "tries++" to increment your tries each time. Finally, you need to put your if statements inside the while loop by using curly brackets. Here is the correct code:
while (tries < 3 && keepgoing == true)
{
if (ask == password)
{
printf("Correct!!!\n");
keepgoing = false;
}
else
{
printf("Incorrect, Try Again!!!\n");
ask = get_int("Enter Password: ");
tries++;
}
}
if (tries == 3)
{
printf("Too many wrong attempts\n");
}