Thursday, September 24, 2009

SWITCH CASE STATEMENT

To make a decision from the number of choices

Decision variable is a single value


Each case will end with break


Syntax:


switch(Integer expression)


{


case condition 1:


Statement 1;


....


break;


case condition 2:


Statement 1;


....


break;


default:


Statement 1;


....


break;


}


Example:


main()


{


int a;


printf(“\n Enter a value:”);


scanf(“%d”,&a);


switch(a)


{


case 1:


printf(“ \nThis is case 1”);


break;


case 2:


printf(“ \nThis is case 2”);


break;


case 3:


printf(“ \nThis is case 3”);


break;


default:


printf(“\nDefault case”);


}


}


Output:


Enter a value:2


This is case 2


NOTE: Without using break in switch case statement executes the case where a match found and all subsequent statement cases and default as well.


Example:


main()


{


int a;


printf(“\n Enter a value:”);


scanf(“%d”,&a);


switch(a)


{


case 1:


printf(“ \nThis is case 1”);


case 2:


printf(“ \nThis is case 2”);


case 3:


printf(“ \nThis is case 3”);


default:


printf(“\nDefault case”);


}


}


Output:


Enter a value:2


This is case 2


This is case 3


Default case