We will learn to use switch case statement in C programming. After completing this tutorial you will be able to use switch case in almost any scenario.
If we need to choose option using only single value or constant then we use switch statement.
Syntax of switch statement:
// code to be executed if case is equal to value1;
// code to be executed if case is equal to value2;
// code to be executed if case doesn't match any value
In above code, if the constant is equal to case 1, the code of first case will execute. If first case is not matched, it will try with and so on if non of the case is matched the code of default: block executes.
If first case is matched and after execution of code, if break; statemet is not found the switch statement will not be terminate instead it again check all the case until last case executes.
Switch statement flow chart
Example of switch statement
//program to print the day of the week according to the number of days entered
# include <iostream>
using namespace std;
cout << "Enter the number of the day : ";
cin >> n;
cout << "Sunday";
cout << "Monday";
cout << "Tuesday";
cout << "Wednesday";
cout << "Thrusday";
cout << "Friday";
cout << "Saturday";
cout << "You entered wrong day";