Basic Loop Help

Hi,

I need help with the programming of a basic loop while loop that keeps repeating until the user has entered either "N" or "Y".

This is what I have got right not but it is not working:

1
2
3
4
5
6
    
     do{ 
        printf("\n\tError! \n\tPlease try again: ");
        scanf("%c", &chr);
        getchar();
        }while(chr!='y' || chr!='Y' || chr!='N' || chr!='n');


Thanks
1
2
3
4
5
6
printf("Y or N?\n");
while(true){ 
   scanf("%c", &chr);
   if (chr=='y' || chr=='Y' || chr=='N' || chr=='n') break;
   printf("\n\tError! \n\tPlease try again: ");
}


The main problem was your logic x != a || x != b will always be true. For it to be false, x would have to be both a and b.
Hi thanks for reply hamsterman.

However i need it to be a do while loop.
Then you just need to implement Hamsterman's logic into a 'while' loop.

The type of loop isn't the problem, it's the conditions on which it runs under. As Hamsterman quite rightly pointed out, it's impossible for result of the conditions to ever be false. I think you want to use the logical 'and' operator.
Last edited on
You could just invert the logic.
1
2
3
do{
    // Stuff
while ( chr != 'y' && chr != 'Y' && chr != 'n' && chr != 'N');


Edit:

You may want to play with the order of the logic evaluations. Putting the most commonly expected responses first will cause a better average big O evaluation time because of the rules of short-circuit logic.
Last edited on
Topic archived. No new replies allowed.