Why the logical operators are not working as expected? [closed]

In your code,

 if (number == 10 || 11 || 12 || 13 || 14 || 15 || 16 || 17 ||18 || 19)

is a wrong approach. You cannot chain the logical operator like that.

As of now, because of the operator precedence, your code is essentially

if ( (number == 10) || 11 || 12 || 13 || 14 || 15 || 16 || 17 ||18 || 19)

which evaluates to either

  • if ( 1 || 11 || 12 || 13 || 14 || 15 || 16 || 17 ||18 || 19)

or

  • if ( 0 || 11 || 12 || 13 || 14 || 15 || 16 || 17 ||18 || 19)

both of which will yield a TRUE value.

You have to use it like

if ((number == 10) || (number ==  11)||(number ==  12).....

As I can see, you’re already using the switch statement, so the if check can be removed altogether. You need to add a default case to handle other numbers. You can add nested switch to get the things done.

Leave a Comment