AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Easycswitch

~60s

Falling through a switch

What does this C program print?

#include <stdio.h>

int main(void) {
    int n = 2;
    switch (n) {
        case 1: printf("A");
        case 2: printf("B");
        case 3: printf("C"); break;
        case 4: printf("D");
        default: printf("E");
    }
    return 0;
}
Show the answer and the worked solution

Correct answer: B.

BC

Worked solution

  1. n = 2 so control jumps to case 2 and prints B.
  2. There is no break after case 2, so execution falls through into case 3 and prints C.
  3. case 3 does end in break, so the switch is left and the output is BC.

Answer: BC.

The idea

Cases in C fall through by default; break is what stops them. Reading a switch as a chain that you jump into, rather than as a set of independent branches, makes the output obvious.

Shortcut. Enter at case 2 and print every label's output until the first break: B, then C, then break.

Common trap. "B" treats each case as a self-contained branch that stops at the next label; in C, cases fall through until a break.

Falling through a switch — Aptitude Question

Falling through a switch: What does this C program print? Answer and worked solution on CodeKairo.

Question

What does this C program print?

#include <stdio.h>

int main(void) {
    int n = 2;
    switch (n) {
        case 1: printf("A");
        case 2: printf("B");
        case 3: printf("C"); break;
        case 4: printf("D");
        default: printf("E");
    }
    return 0;
}

Options

  1. B
  2. BC
  3. BCD
  4. BCDE
Show the answer and the worked solution

Correct answer: B. BC

Worked solution

  1. n = 2 so control jumps to case 2 and prints B.
  2. There is no break after case 2, so execution falls through into case 3 and prints C.
  3. case 3 does end in break, so the switch is left and the output is BC.

Answer: BC.

The idea

Cases in C fall through by default; break is what stops them. Reading a switch as a chain that you jump into, rather than as a set of independent branches, makes the output obvious.

Shortcut. Enter at case 2 and print every label's output until the first break: B, then C, then break.

Common trap. "B" treats each case as a self-contained branch that stops at the next label; in C, cases fall through until a break.

All Programming Fundamentals questions · placement mock tests