Previous | Home | Next |
# switch statement
The switch statement allows you to select from multiple choices based on a set of fixed values for a given expression. Switch statement is used to switch the multiple choices.
It has a built in multiple - branch structure and work similar to if else ladder generally. The input value to to the switch statement construct is a int or char variable. Note that no float or any other data is allowed. This input variable is compared against a group of integer constant.
All the statements in and after the case in which there is a match is executed until a break statement is encountered or end of switch is reached. We are also allowed to give a default case which will be executed if no other statement match is found.
switch(expression){ case value1: /* execute unit of code 1 */ break; case value2: /* execute unit of code 2 */ break; ... default: /* execute default action */ break; }
All the statements in and after the case in which there is a match is executed until a break statement is encountered or end of switch is reached. We are also allowed to give a default case which will be executed if no other statement match is found.
Syntax
switch (integer expression) case 1: do this; case2: do this; //default :do this; }
#include <stdio.h> int main (void) { char ch; printf ("\nEnter Character x,y or z: "); ch = getchar (); switch (ch) { case 'x' : printf ("You Entered x"); break; case 'y' : printf ("You Entered y"); break; case 'z' : printf ("You Entered z"); break; default : printf ("You Didnot Entered x, y or z"); } return 0; }
Previous | Home | Next |