Friday, July 1, 2011

Switch Case Statement in C

0 comments
                    The switch case statement allows you to select from multiple choice based on a set of fixed value for a give expression.The value of the variable given into switch is compared to the value following each of the cases.And when one value matches the value of the variable,the computer continues executing the program from that point.


Syntax of the 'switch case' statement is:
switch(expression)
{
case value1:  /*execute code1*/
break;
case value2: /*execute code2*/
break;
.....
default: /*execute default action*/
break;
}

Example:
/*Program to convert number into word*/
#include<stdio.h>
void main()
{
int num;
printf("Enter a number:\n");
scanf("%d",&num);
switch(num)
{
case 1:
printf("ONE!\n");
break;
case 2:
printf("TWO!\n");
break;
case 3:
printf("THREE!\n");
break;
case 4:
printf("FOUR!\n");
break;
case 5:
printf("FIVE!\n");
break;
case 6:
printf("SIX!\n");
break;
case 7:
printf("SEVEN!\n");
break;
case 8:
printf("EIGHT!\n");
break;
case 9:
printf("NINE!\n");
break;
case 0:
printf("ZERO!\n");
break;
default:
printf("Invalid Number!\n");
break;
}
getch();
}
In the switch case statement,the selection is determined by the value of an expression that you specify,which is enclosed between the parentheses after the keyword switch.The data type of value which is returned by expression must be an integer value otherwise the statement will not compile.when a break statement is executed,it causes execution to continue with statement following the closing brace for switch.The default statement is the default choice of the switch statement if all cases statement are not satisfy with expression.
Continue reading →