Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Do…while loop only working for one condition in C

Can somebody explain why the do…while loop is repeating itself in for b, B, c, or C but not if you put a or A? This is a subpart of the code I am writing up. I want to limit the number of input to only a, b, or c so that any other input just repeats itself until it gets one of the correct letters.

do{
        printf("Which package would you like to select? A, B, or C ");
        scanf(" %c", &package_choice);
}while(toupper((unsigned char)package_choice) != 'A' && 'B' && 'C');

I have changed the && to || but it repeats itself over and over no matter the input. I went through and did the (unsigned char)package_choice) != to each letter to see if that changed anything but I got the same result. I’m still learning C in school and am having a hard time understanding some of the basic formats that go along with C. Thank you for any help!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This line is not doing what you think it does:

while(toupper((unsigned char)package_choice) != 'A' && 'B' && 'C');   

… what the above actually does is logically equivalent to this:

while(toupper((unsigned char)package_choice) != 'A' && ('B' != 0) && ('C' != 0));

… and since ‘B’ (aka ASCII value 66) and ‘C’ (aka ASCII value 67) are always not equal to zero, those parts of the expression will always trivially evaluate to true and therefore have no effect on the behavior of the test.

Rewritten to properly express the logic you intended, the expression should look like this:

while(toupper((unsigned char)package_choice) != 'A' 
   && toupper((unsigned char)package_choice) != 'B' 
   && toupper((unsigned char)package_choice) != 'C');   
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading