I’m trying to learn how to program in C and have stumbled into a problem that seems like it should have been a simple fix, but it’s giving me more issues then I anticipated. I’m trying to created a number guessing game, where you get three chances to guess the number, but my issue is that the Do While loop wont break when the right answer is guessed. Here is the function:
void Win_Search(int lucky[],const int MAX, int user_entry, int i)
{
int j=0;
do {
j++;
printf("Please enter a number between 0 and 100\n");
scanf("%d",&user_entry);
for(i = 0; i < MAX; i++)
{
if(user_entry==lucky[i])
{
printf("winner\n");
}
}
} while(user_entry==lucky[i]||j<3);
}
Basically it’s supposed to loop through the array lucky[i] and check to see if the user_entry equals any of the 20 numbers in the array. As of right now it loops through, recognizes if a winning number has been selected from the array, but doesn’t break from the array.
when I change it to
}while(user_entry!=lucky[i]||j<3);
it completely ignores the counter and just loops forever.
I don’t want to use break because everything I’ve read about it talks about it’s poor programming practice. Is there another way to break, or have simply just made a mistake thats causing this issue.
Thanks in advance.
You wrote
while (user_entry == lucky[i]..)which translates toas long as user_entry is equal to lucky[i] keep on looping. Which is clearly not what you intend to do.Transform your condition to
} while (user_entry != lucky[i] && j < 3);and you should be fine. This will translate in plain english toas long as user_entry is different of lucky[i] AND j is inferior to 3, keep looping.But using this, you test on the value of
lucky[i]even whenimeans nothing ( when i is equal to max, you don’t want to test it, and this goes in the domain of undefined behavior).But if you realy dont want to use
breakkeyword, one solution is to use a flag. Set it to 1 before you start to loop, and change it to 0 when the good answer is found. Your code will become