Sunday, December 13, 2009

4.6 THE switch STATEMENT

The switch statement causes a particular group of statements to be chosen from several available groups.The selection is based upon the current value of an expression which is included within the switch statement.

The general form of switch statement is
switch (expression) statement

where expression results in an integer value.Note that expression may also be of type char ,since the individual characters have equivalent integer values.

A simple switch statement is illustrated below.In this example choice is assumed to be a char-type variable.

switch(choice=getchar()) {


case 'r':
case 'R':
printf("RED");
break;


case 'w':
case 'W':
printf("WHITE");
break;


case 'b':
case 'B':
printf("BLUE");

}

Thus, RED will be displayed if choice represents either r or R.white will be displayed if choice represents either w or W,and  BLUE will be displayed if choice represents either b or B.Nothing will be displayed if any other character has been assigned to choice.

No comments:

Post a Comment