Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

do...while loop problem

Status
Not open for further replies.

Oxymoron

Technical User
Dec 17, 2000
168
GB
Hello,

just a quick question.
Does anyone know why this do...while loop wont evaluate to true when either 'y' or 'n' is entered?

do
{
printf("\nDo you wish to add more results manually?: ");
scanf(" %c", &choice);
}while((choice != 'y') || (choice != 'n'));

However, when the while loop condition is just "while(choice != 'y');" and 'y' is entered, the condition evaluates to true and loop is exited.

And yes, I have considered the carriage return, hence the space before the "%c" in scanf.

Any and all suggestions welcome!

Thanks everyone.

Oxy

we are all of us living in the gutter.
But some of us are looking at the stars.
 
Change it to:

while((choice != 'y') && (choice != 'n'))


Since you are negating you need to use "&&" (and) instead of "||" (or).
 
*********************************************************************
you might also do it like this:
Code:
do
{
      printf("\nDo you wish to add more results manually?: ");
      scanf(" %c", &choice);
}while(!( (choice == 'y') || (choice == 'n') ));
 
Both Dsanches2 and Leibnitz have corrected erroneous condition. There are some posts about logical expressions on this forum last week.
Let's remember old good boolean (and classic;) logic. We must terminate the loop when Predicate1 or Predicate2 is true. Then we must continue the loop while not (P1 or P2). Well:
not (P1 or P2) == not P1 and not P2.
not (P1 and P2) == not P1 or not P2.
If P(x,y): x == y then not P(x,y) is x != y...
 
... I find it easier just to read out loud in English what I've written in code:

"while the user didn't type one of (Y or N), ask for another key..."

Or,

"While the user didn't type Y, AND he didn't type N, ask for another key.."
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top