Loops In C/C++ Language

Switch Case Statement IN C/C++

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<stdio.h>
#include<conio.h>     
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.