Thursday, 29 May 2014

Switch-Case Statement in C

While if is good for choosing between two alternatives, it quickly becomes typical when several alternatives are needed. C's solution to this problem is the switch statement. The switch statement is C's multiple selection statement. It is used to select one of several alternative paths in program execution and works like this: A variable is successively tested against a list of integer or character constants. When a match is found, the statement sequence associated with the match is executed. The general form of the switch statement is:
Syntax:
switch(expression)
{
 case constant1: statement sequence; break;
 case constant2: statement sequence; break;
 case constant3: statement sequence; break;
 .
 .
 .
 default: statement sequence; break;
}

Expression is always a constant(or integer-valued constants). If expression is character then it will take as ascii value of that character. Each case is labelled by one, or more, constant expressions (or integer-valued constants). The default statement sequence is performed if no matches are found. The default is optional. If all matches fail and default is absent, no action takes place. When a match is found, the statement sequence associated with that case are executed until break is encountered. An example program follows:
#include
int main()
{
 int i;
 printf("Enter a number between 1 and 4");
 scanf("%d",&i);
 switch (i)
 {
  case 1:
   printf("one");
   break;
  case 2:
   printf("two");
   break;
  case 3:
   printf("three");
   break;
  case 4:
   printf("four");
   break;
  default:
   printf("unrecognized number");
} /* end of switch */ 
Output:
Enter a number between 1 and 4:
2
two
This simple program recognizes the numbers 1 to 4 and prints the name of the one you enter. The switch statement differs from if, in that switch can only test for equality, whereas the if conditional expression can be of any type. Also switch will work with only int and char types. You cannot for example, use floating-point numbers. If the statement sequence includes more than one statement they will have to be enclosed with {} to form a compound statement.

The break statement at the end of each case cause switch statement to exit. If break statement is not used, all statements below that case statement are also executed. In above example ,in case 2 break statement is not there then output will be : two three  , because in case 3 ,break statement is there then it will be break after printing the three.
Output:
Enter a number between 1 and 4:
2
twothree

0 comments :

Post a Comment