0
0
Cprogramming~20 mins

Switch vs if comparison - Practice Questions

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Switch vs If Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of switch with fall-through
What is the output of this C code snippet?
C
#include <stdio.h>

int main() {
    int x = 2;
    switch (x) {
        case 1:
            printf("One\n");
        case 2:
            printf("Two\n");
        case 3:
            printf("Three\n");
            break;
        default:
            printf("Default\n");
    }
    return 0;
}
A
One
Two
Three
B
Two
Three
C
Two
D
Default
Attempts:
2 left
💡 Hint
Remember that switch cases fall through unless you use break.
Predict Output
intermediate
2:00remaining
If-else equivalent output
What is the output of this if-else code?
C
#include <stdio.h>

int main() {
    int x = 3;
    if (x == 1) {
        printf("One\n");
    } else if (x == 2) {
        printf("Two\n");
    } else if (x == 3) {
        printf("Three\n");
    } else {
        printf("Default\n");
    }
    return 0;
}
A
One
B
Two
C
Three
D
Default
Attempts:
2 left
💡 Hint
Check which condition matches the value of x.
Predict Output
advanced
2:00remaining
Switch with non-constant case labels
What error does this code produce?
C
#include <stdio.h>

int main() {
    int a = 1;
    int b = 2;
    switch (a) {
        case b:
            printf("B\n");
            break;
        default:
            printf("Default\n");
    }
    return 0;
}
AOutput: Default
BRuntime error: segmentation fault
COutput: B
DCompilation error: case label does not reduce to an integer constant
Attempts:
2 left
💡 Hint
Case labels must be constant expressions in C.
🧠 Conceptual
advanced
2:00remaining
Difference in evaluation between switch and if
Which statement about switch and if is true in C?
ASwitch evaluates the expression once and jumps to matching case; if evaluates conditions sequentially.
BSwitch evaluates all cases before executing any code.
CIf evaluates all conditions before executing the matching block.
DSwitch can evaluate ranges like if conditions can.
Attempts:
2 left
💡 Hint
Think about how switch jumps directly to a case.
Predict Output
expert
2:00remaining
Output of nested switch and if
What is the output of this code?
C
#include <stdio.h>

int main() {
    int x = 1, y = 2;
    switch (x) {
        case 1:
            if (y == 2) {
                printf("A\n");
                break;
            }
            printf("B\n");
            break;
        case 2:
            printf("C\n");
            break;
        default:
            printf("D\n");
    }
    return 0;
}
A
A
B
B
C
C
D
D
Attempts:
2 left
💡 Hint
Check the if condition inside case 1 and where the breaks are.