Search code examples
cwhile-loopswitch-statementcaseassignment-operator

Can I use an assignment in a switch case?


Baby programming student here. An assignment asks for me to use a few loops to count from 1 - 100, and in one of the loops I have to include a switch statement that prints some things depending on the conditions. Here is what the assignment is: "Create a basic program that accomplishes the following requirements:

  1. Uses a for statement to count from 1 to 100.
  2. Uses a while statement to count from 1 to 100.
  3. Use a do while statement to count from 1 to 100.
  4. Using a switch statement in one of the loops , print to the screen if a number is: Less than or equal to 10, Greater than or equal to 11 but less than 20, Greater than 21."

I can complete the looping statements just fine, and I can write a switch statement, but putting a switch statement inside of a loop that is already counting seems impossible. From my understanding, a case in a switch statement must be an integral value (like '1') and cannot be an assignment (like 'counter <= 10'). I have done so much research and found no help or clarity from my professor or any youtube tutorial. I am at wits end here; is there something I'm just not understanding about switch statements? I feel so lost.


Solution

  • You can have several case labels before the same statement:

        for (int i = 1; i <= 100; i++)
        {
            switch (i)
            {
            case 1: case 2: case 3: case 4: case 5:
            case 6: case 7: case 8: case 9: case 10:
                printf("%d is less than or equal to 10\n", i);
                break;
            case 11: case 12: case 13: case 14: case 15:
            case 16: case 17: case 18: case 19:
                printf("%d is greater than or equal to 11 but less than 20\n", i);
                break;
            case 20:
            case 21:
                /* nothing printed for 20 or 21? */
                break;
            default:
                /* cases 22 to 100 */
                printf("%d is greater than 21\n", i);
                break;
            }
        }