Nearby lessons

41 of 124

C - Switch Statement

Switch Statement is one of the foundational topics in C programming. This lesson explains The switch Statement with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

The switch Statement

switch is perfect when one value is compared against many fixed constants (like a menu). It jumps straight to the matching case.

In simple words: switch is a menu — the expression is the order, each case is one dish, and break means "that's all, I'm done". It jumps straight to the matching dish instead of checking every option in order.
Example01
CCode Cell
1switch (expression) {
2 case value1: statements; break;
3 case value2: statements; break;
4 ...
5 default: statements;
6}

The switch Statement

Trainer's Note: The break is essential in switch — without it, execution falls through to the next case. The default case is optional and runs when nothing matches. Also remember: switch works with integer and character expressions, not floats or strings.
Example02
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int day;
6 printf("Enter day number (1-3): ");
7 scanf("%d", &day);
8 
9 switch (day) {
10 case 1: printf("Monday\n"); break;
11 case 2: printf("Tuesday\n"); break;
12 case 3: printf("Wednesday\n"); break;
13 default: printf("Other day\n");
14 }
15}
Output

Enter day number (1-3): 2
Tuesday
      
📝 Key Takeaways
  • if runs a block when the condition is true; else covers the false case.
  • if-else-if ladder chooses the first true condition.
  • Nested if = an if inside another if.
  • switch jumps to a matching case; remember break and default.
  • switch works with int/char, not float or string.
  • Ternary ?: is a one-line if-else.

🧠 Test Your Knowledge

4 Questions
Progress: 0 / 4