The switch Control Statement ---------------------------- The "if-else" chain is used in programming applications where one set of instructions must be selected from many possible alternatives. The "switch" statement provides an alternative and has a shorter format. The format is: switch (expression) { case value_1: statement1_1; statement1_2; : statement1_n; break; case value_2: statement2_1; statement2_2; : statement2_n; break; : : default: statementm_1; statementm_2; : statementm_n; } Note: Look carefully where the colons are and semicolons (see book page 143 and page 144. An example of it's usage is: switch (a) { case 1: printf("value is 1\n"); break; case 2: printf("value is 2\n"); break; default: printf("value is something else\n"); } The switch statement above takes the variable called "a" and checks it's contents. If it has the value of 1 it goes to the case 1's area. If it has a value of 2 it goes to the case 2's area. If it has any other value, it goes to the default area. Let's try a problem. Problem: Let Monday thru Friday be represented by numbers 1-5. Set up a condition such that on Monday and Wednesday it will say "go to class". On the other days, "party the night before and sleep in". Input the weekday via args. #include #include main(int argc, char **argv) { int day = atoi(argv[1]); switch (day) { case 1: case 3: printf("go to class\n"); break; case 2: case 4: case 5: printf("party the night before and sleep in\n"); break; default: /* do nothing */ break; } } The output is: delacroix:/u/greg/VIZA652/c_book2% pro4 1 go to class delacroix:/u/greg/VIZA652/c_book2% pro4 2 party the night before and sleep in delacroix:/u/greg/VIZA652/c_book2% pro4 3 go to class delacroix:/u/greg/VIZA652/c_book2% pro4 4 party the night before and sleep in delacroix:/u/greg/VIZA652/c_book2% pro4 5 party the night before and sleep in delacroix:/u/greg/VIZA652/c_book2% pro4 6 Exercises 4.4 -- Problem #4 --------------------------- Determine why the if-else chain in program 4-5 (in C book) cannot be replaced with a switch statement? Answer: The if-else statement in there contains a range of values. You would need to test for each value like >= 50000.00 . case 50000.00 case 50000.01 case 50000.02 : Can you imagine how long this would be?? Thus you cannot do it since the numbers of floating point and there is a large range of numbers that would exhaust your computer's memory and your time (in fact you would never finish it).