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?
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.
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With