Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch vs if ... else if ... else

Tags:

c

I have a question. I'm studying for my exam and I don't know how to do answer this. Basically I have to change the instructions if...else if... else, to a instruction switch in order that the output of the program stays the same.

void main()
{
    int x;
    x = 1;
    for (int i = 1; i < 10; ++i) {
        if (i <= 3)
            do {
                x += i;
                if (x >= 4)
                    break;
            } while (i % 2 == 0);
        else if ((i > 3) && (i < 5))
            x += 2;
        else
            continue;
    }
    while (x > 0) {
        printf(" x=%d ", x);
        x -= 1;
    }
    system("pause");
}

Am I allowed to do a switch inside of the for loop?

like image 533
Marco Avatar asked Jun 14 '26 16:06

Marco


2 Answers

Of course you can. A for loop controls the execution of a statement and a switch block is a statement.

Given that i is in the inclusive range of 1 to 9, you can replace the if block with

switch (i){
case 1: case 2: case 3:
    // that replaces 'if (i <= 3)'
    // ToDo - the code here
    break; // to obviate follow-through.
case 4:
    // that replaces 'if ((i > 3) && (i < 5))'
    // ToDo - the code here
    break;
default:
    // that replaces 'else'
    continue; // note that this is for the for loop, not the switch
}

Note that the behaviour of if (x >= 4) break; is not changed by this refactoring.

I'm not convinced however that replacing the if block with a switch is the right thing to do here: the boundaries i <= 3 and i >= 5 are less naturally handled with a switch; perhaps changing the type of i to unsigned and handling case 0: explicitly would alleviate this somewhat.

like image 56
Bathsheba Avatar answered Jun 17 '26 11:06

Bathsheba


Something like this should work

void main()
{
    int x;
    x = 1;
    for (int i = 1; i < 10; ++i) {
        switch (i) {
            case 1:
            case 2:
            case 3:
                 do {
                     x += i;
                     if (x >= 4)
                         break;
                 } while (i % 2 == 0);
                 break;
            case 4:
                 x += 2;
                 break;
            default:
                continue;
                break;
         }
    }
    while (x > 0) {
        printf(" x=%d ", x);
        x -= 1;
    }
    system("pause");
}
like image 34
Mike Avatar answered Jun 17 '26 09:06

Mike