switch Statement in C
The switch case statement is an alternative to the if else if ladder that can be used to execute the conditional code based on the value of the variable specified in the switch statement. The switch block consists of cases to be executed based on the value of the switch variable.
Syntax of switch
switch (expression) {
case value1:
statements;
case value2:
statements;
....
....
....
default:
statements;
}
Note: The switch expression should evaluate to either integer or character. It cannot evaluate any other data type.
Flowchart of switch
Example of switch Statement
C
// C Program to illustrate the use of switch statement #include <stdio.h> int main() { // variable to be used in switch statement int var = 2; // declaring switch cases switch (var) { case 1: printf ( "Case 1 is executed" ); break ; case 2: printf ( "Case 2 is executed" ); break ; default : printf ( "Default Case is executed" ); break ; } return 0; } |
Case 2 is executed
Decision Making in C (if , if..else, Nested if, if-else-if )
The conditional statements (also known as decision control structures) such as if, if else, switch, etc. are used for decision-making purposes in C programs.
They are also known as Decision-Making Statements and are used to evaluate one or more conditions and make the decision whether to execute a set of statements or not. These decision-making statements in programming languages decide the direction of the flow of program execution.