Before we use Switch statement we must Understand the Switch Case Statement
In ca Language Switch case statements are used to execute only specific case statements (Block of statements) based on the switch expression.
Syntax of Switch Case Statment
switch (expression)
{
case label1:
statements;
break;
case label2:
statements;
break;
.
.
.
default: statements;
break;
}
When Switch statement gets a value( may be variable constant or expression) then its match with cases below . when a case is match then the block of statement in that case will be executes and the break statement break the process and control transfer out from Switch Case statements. if no one case is match then the last block which is default label will be executed.
Example 1: input a number and match these number in given cases and execute the statement of matching block.
#include #include int main() { int x; printf("Enter a Number \n"); scanf("%d",&x); switch(x) { case 1: printf("One \n" ); break; case 2: printf("Two \n" ); break; case 3: printf("Three \n" ); break; case 4: printf("Four \n" ); break; default : printf("You Enter The value other then 1,2,3,4 \n" ); } return 0; }
Explanation of above example:
int x;
this is initialization and declaration of variable which tell to complier that x is an integer variable and have a value 1.
printf("Enter a Number \n");
This statment display a message "Enter a Number " and \n take cursor to next line.
scanf("%d",&x);
This get the number from user and store in x.
switch(x)
This Switch statement check the number and transfer the control to the matching Case. Matching Case execute the statement in that block and then take control after the Case Block.
return 0;
This statement is the "Exit status" of the program. In simple terms, program ends.
Declaring and Initializing Local Variable in C
Declaring and Initializing Global Variable in C Language
Printf Function In C Language
Sacnf Function In C Language
for Loop in C Language
While Loop in C Language
Do While Loop in C Language
Switch Case Statement IN C
IF -Else Statement IN C
Break Statement IN C /C++
User Define Function IN C /C++
Cout/Cin Function IN C /C++
Array IN C /C++
Two Dimensional Array IN C /C++
String In IN C /C++
Pointer In IN C /C++
Const and volatile keyword IN C /C++
Class and Object in C++
Function Over Loading in C++
Character Array In C++
Constructor in C++
Operator overloading in C++
Function Templates in C++
ATM Sample Project In Simple C Language
Find Area of Shape Using Function In C++