Switch Case Statements are special type of Conditional Statements (Selection Control Mechanism) , Basically they are used as a alternative for the long if statements used to compare integral values , By integral values we mean the values that can be expressed as an integer eg :- Characters , Integers , Numbers etc. Syntax:- Code: switch(Variable_to_be_checked) { // --- See Below for Explanation [1] case OPTION : CodeTOBeExecuted; break; case OPTION2 : CodeToBeExecuted; break; case OPTION3 : CodeToBeExecuted; break; // ............................................. // ............................................. // See Below for explanation [2] default : CodeToBeExecuted; break; } Explanation:- Firstly we declare a switch statement followed by Circular Brackets ‘(’ and ‘)’, In between is the variable that needs to be checked below. The switch-case body starts with ‘{’ and ends with ‘}’ all the conditions should be placed inside the Curly Brackets only. [1] – Then we declare a ‘case’ statement which is followed by an integral value and a colon ‘:’. After the colon we start the case body under which the specified code is executed if the case condition evaluates to true. The Integral value is compared with the variable (which we added in the switch() statement). It is same as the following if statement:- Code: if(variable == OPTION) [2] – Then at the end of our code we declare a ‘default’ case/statement followed by a colon , this case is executed if all above conditions evaluate to false. This statement can be considered same as else statement in if-else structure. The default statement is optional. Note: Case values can only be constant integral expressions. It basically means that OPTION (Used Above) should be an integral constant and not a variable. Menu Driven Program Now that we know something about switch-case statements lets create a basic Menu-Driven Program using Switch-Case. menu.c Code: #include<stdio.h> int main() { int option; printf("\n==== Welcome to Different Ways of Saying Hello! :D ====\n\n\n"); printf("Option (1-3) : "); scanf("%d",&option); switch(option) { case 1 : printf("Hello!"); break; case 2 : printf("Heya!"); break; case 3 : printf("Hola!"); break; default : break; } } Output :- Code: ==== Welcome to Different Ways of Saying Hello! :D ==== Option (1-3) : 1 Hello! That’s all for this tutorial stay tuned for more.
Re: Introduction to Switch-Case Statements and Menu-Driven Programs in C very simple and gud explanation sir