Search code examples
c++loopswhile-looplogical-operators

While Loop when to use OR or AND?


I need help with this simple question.

I'm starting to learn more about while loops and I'm not sure what I'm doing wrong.

Here's a snippet of the code that I'm working on, so when I'm using or in while loop the loop executes indefinitely. But when I use AND the loop stops can somebody please explain? Shouldn't OR be used instead as per definition?

void displayMenu() {
    char option;
    while (option != 'Q' or 'q') { //And or OR?
        cout << "P - Print numbers" << endl;
        cout << "A - Add a number" << endl;
        cout << "M - Display mean of the numbers" << endl;
        cout << "S - Display the smallest number" << endl;
        cout << "L - Display the largest number" << endl;
        cout << "Q- Quit" << endl;
        cout << "Choose Your Option-" << endl;
        cin >> option;
        if (option == 'P' or 'p')
            Print();
    }
}

Solution

  • You have phrased your condition (option != 'Q' or 'q') like you speak it.
    "option not upperQ or lowerQ".
    That is understood by the compiler as "option is not upperQ; or q", where "q" is a non zero thing. Nonzeros are interpreted as "true". So the whole thing always evaluates to "true", always, even for option having a values like 'Y' or '2'.

    You have to rephrase much less coloqually as
    "option is not 'Q' and it is not 'q' "
    and you have to use the appropriate operators. Using additional () to make sure that what you mean is understood does not hurt.

    That is done as

    ( (option != 'Q') && (option != 'q') ) 
    

    Using or, or in this case and instead of the logical && is possible in certain situations, and the additional () are not required either. The main issue is however with your choice of "or" instead of "and" and using the () is a safe way as long as you are not very familiar with the operators and their order of evaluation in expressions like this one.

    Why exactly you need to use && ("and") instead of or or || is a question of what happens with the two interesting letters. Lets take 'Q' it obviously is one of the two you are looking for. But it is not 'q'. So the second part of the condition with is true. With || that is sufficient and the whole thing is evaluated to "true" and the loop continues - obviously not what you want. The same is for 'q', it is not 'Q' and there for || continues.
    What you actually want is "neither" and that is the same as "not this and not that". Hence you need "not and not", !a && !b or more bluntly explicit (option != 'Q') && (option != 'q').
    That can be reprhased with implicit knowledge of operator precedence (look it up and try to memorize) to option != 'Q' && option != 'q'.