What is the purpose of the switch() statement? Explain with the help of one example.

The switch() statement is used to test a variable against a list of values, called cases, and execute the code corresponding to the first matching case. It is particularly useful when you have multiple conditions based on the value of a single variable. The switch statement can be more efficient and easier to read compared to a series of if-else statements, especially when you have many possible conditions to check.

The syntax of a switch statement typically includes:

  • A variable or expression being tested.
  • A series of case labels that specify the values to compare.
  • A break statement to exit the switch once a match is found. If break is omitted, execution continues to the next case (this is called “fall-through”).

Example:

int day = 3;
switch(day) {
case 1:
printf(“Monday”);
break;
case 2:
printf(“Tuesday”);
break;
case 3:
printf(“Wednesday”);
break;
default:
printf(“Invalid day”);
}

Output: Wednesday

In this example, the value of day is 3, so the program will output “Wednesday.” If the value were not one of the cases (e.g., 5), the default case would be executed, printing “Invalid day.”