0

Hello!

I have a problem about creating a menu, the switch statement doesn't break. Could somebody please help?

The code is:

        do
        {
            /* ...get input... */
            switch(choice)
            {
            case 1:
                submenu();
                break;
            case 2:
                submenu2();
                break;
            case 3:
                printf("\nThe program quits.\n");
                exit(0);
            default:
                printf("\nNo such menu item!\n\n");
                break;
            }
        }
        while(choice != 1 || choice != 2 || choice != 3);

After calling submenu or submenu2 it executes the corresponding method, but after, it returns to the get input part again. What am I missing here?

Thanks in advance!

4
Contributors
6
Replies
24
Views
4 Years
Discussion Span
Last Post by blackrainbowhu
0

That would mean that the input should be 1 AND 2 AND 3 in the same time, not?

EDIT: it's working the way you said but why? Could you please explain it? Thx!

Edited by blackrainbowhu: solution

0

That would mean that the input should be 1 AND 2 AND 3 in the same time, not?

You're comparing inequality, not equality. So if the input is not 1, not 2, and not 3 then the loop will continue.

0

The reason why the && condition worked was because of the following reasons:
when you compare something with the and (&&) logical operator then even if the first case fails, then the system does not need to go and check the remaining of the conditions.
for your example if we use the && instead of the ||

while(choice != 1 && choice != 2 && choice != 3);

then according to the boolean logic for and (&&)

Suppose:
A && B = C

A B C
0 0 0
0 1 0
1 0 0
1 1 1

so if choice had value 1 then the condition choice !=1 fails and then the system does not check ahead as it knows that the condition has failed, and to get out of the loop.

However if the conditions were using or (||) as shown in your example:

while(choice != 1 || choice != 2 || choice != 3);

then if choice has the value 1 then your condition will always be true because your other conditions will be true even though your first condition failed, and your loop will not end.

A || B = C

A B C
0 0 0
0 1 1
1 0 1
1 1 1

i hope that this helped you in understanding the basics.

0
  while(choice != 1 && choice != 2 && choice != 3);

It means repeat above until the value is apart from 1,2 or 3(until the statement is true).

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.