SQL PHP HTML ASP JavaScript articles and free scripts to download
 

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

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

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;
}




Post Comment This is for short comments only. Use the forum for more discussions.
Name
Email( not to be displayed)Privacy Policy
1+2=This is to prevent automatic submission by spammers. Please enter the result of the sum as asked


Join Our Email List
Email:  
For Email Newsletters you can trust



Basic of C
C Sections
HTML . MySQL. PHP. JavaScript. ASP. Photoshop. Articles. FORUM Contact us

©2000-2014 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer