Home > Software engineering >  How to ask question continuously until it meets requirements of having to meet a condition in c
How to ask question continuously until it meets requirements of having to meet a condition in c

Time:09-24

I am using the cs50 online IDE so I am also using the cs50 library at the top. I am trying to make it keep asking the question "Are you okay?" until you either say "y" or "n" (upper or lowercase).

#include <cs50.h>
#include <stdio.h>

int main(void)
{
 
    char answer;
    do
    {
        char answer = get_char("are you okay Y/N ");
        if (answer == 'y' || answer == 'Y')
        {
            printf("you are okay");
        }
            else if (answer == 'n' || answer == 'N')
        {
            printf("you are not okay ");
        }

    }
   
    while(answer != 'y' || answer != 'Y' || answer != 'n' || answer != 'N');
    
}

CodePudding user response:

When learning boolean logic in C, common sense will get you very far. That is: make it a habit of saying the lines you write out loud/in your head:

while(answer != 'y' || answer != 'Y' || answer != 'n' || answer != 'N');

translated to English:

"while the answer is not y or it is not Y or it is not..."

Here you should smell a fish. Correct English/logic would rather be:

"while the answer is not y and it is not Y and..."

Common sense aside, De Morgan's Laws is pretty much necessary prerequisite knowledge before studying any programming.

  • Related