The switch Statement in C Language




The switch statement is very powerful decision making statement. It reduces the complexity of the program. Hence increases the readability of the program. Switch statement accepts single input from the user and based on that input executes a particular block of statements.

Syntax of switch statement:
switch(expression){
case constant 1:
perform this;
case constant 2:
perform this;
case constant 3:
perform this;
case constant 4:
perform this;
.
.
.
default:
perform this;
}

Control passes to the statement whose case constant-expression matches the value of switch ( expression ). The switch statement can include any number of case instances, but no two case constants within the same switch statement can have the same value. Execution of the statement body begins at the selected statement and proceeds until the end of the body or until a break statement transfers control out of the body. Please make a note that using default case is optional.

Example 1:

int a = 2;
switch(a){
case 1:
printf(“1”);
case 2:
printf(“2”);
}
Output:
2

Example 2:

int a = 2;
switch(a){
case 1:
printf(“1\n”);
break;
case 2:
printf(“2\n”);
break;
default:
printf(“No match”)
}
Output:
2

Example 3:
char a = ‘A’;
switch(a){
case ‘B’:
printf(“B\n”);
break;
case ‘A’:
printf(“A\n”);
break;
default:
printf(“No match”)
}
Output:
A


Responses

0 Respones to "The switch Statement in C Language"

Post a Comment

 

Total Pageviews

Return to top of page Copyright © 2011 | Kuppam Engineering College Converted into Blogger Template by Mohan Murthy