swtich statement in C program

Switch statement is used to execute a part of the code block based on the condition set. The condition can be checked by a series of case statements and if found TRUE then that particular set of code is executed. Here is the syntax for the a standard switch statement in C program.
switch( expression )
{
 case value1
  code block 1 
Break; 

case value2
  Code block 2
Break; 

Default;
Code block for default 
}

case

Here the value of expression is check for matching with value given under case. If it matches then the code block in this case will be executed.

break (optional )

When the compiler executes break statement it comes out of the switch statement. So by keeping a break statement in our code block of a case comparison we will stop or end the code block. If we don't use a break statement then complier will execute all the balance statement till the end of the switch which will result in undesired result.

default ( optional )

This is optional block of code gets executed if none of the case statements matches with expression or became true. Usually it is kept towards end after all the case statements are over ( within switch ). Let us try switch statement with an example. We will ask to enter Grade from A to D and based on this input we will display a message saying the grade. If our entered character ( or grade ) does not match with any of the case statements then we will execute the default code with a message. Here is the code.
#include <stdio.h>
int main(void){
char var;
printf(" Please enter your Grade From A to D \n");
var=getchar();

switch(var)
{
case 'A':
printf("You got A grade ");
break;

case 'B':
printf("You got B grade ");
break;

case 'C':
printf("You got C grade ");
break;

case 'D':
printf("You got D grade ");
break;

default:
printf("You entered wrong grade ");
 }
return 0;
}
Switch with matching more than one condition
#include <stdio.h>
int main(void){
 int my_int=8; // Integer constant

switch(my_int){
case 1:
case 2:
case 3:
case 4:
case 5:
printf("Your entered number between 1 and 5,  %d",my_int);
break;

case 6:
case 7:
case 8:
case 9:
case 10:
printf("Your entered number between 6 and 10,  %d",my_int);
break;

default:
printf("No matching %d",my_int);
 }
return 0;
}
Output is here
Your entered number between 6 and 10, 8
Visitors Rating
Your Rating




Post your comments , suggestion , error , requirements etc here




We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2019 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer