UMBC CS 201, Fall 98
UMBC CMSC 201 & 201H Fall '98 CSEE | 201 | 201 F'98 | lectures | news | help

Efficiency

The Task

Print the day of the week that corresponds to an integer in the range of 0 through 6, where 0 is Sunday and 6 is Saturday

Program snippet using if

if(day == 0) { printf("Sunday\n"); } if(day == 1) { printf("Monday\n"); } if(day == 2) { printf("Tuesday\n"); } if(day == 3) { printf("Wednesday\n"); } if(day == 4) { printf("Thursday\n"); } if(day == 5) { printf("Friday\n"); } if(day == 6) { printf("Saturday\n"); } if (day < 0 || day > 6) { printf("Error - unexpected value for day\n"); printf("Should be 0-6. Value is %d\n", day); }

Note:
  1. The value of day must be checked at
    every if, whether or not the day has
    been matched and printed.
  2. A complex test is necessary to handle
    an error and print the error message.


Using Cascading if/else

if(day == 0) { printf("Sunday\n"); } else if(day == 1) { printf("Monday\n"); } else if(day == 2) { printf("Tuesday\n"); } else if(day == 3) { printf("Wednesday\n"); } else if(day == 4) { printf("Thursday\n"); } else if(day == 5) { printf("Friday\n"); } else if(day == 6) { printf("Saturday\n"); } else { printf("Error - unexpected value for day\n"); printf("Should be 0-6. Value is %d\n", day); }

Note:
  1. The value of day must be checked at
    every if only until a match is found.
    The rest of the tests are then skipped.
  2. Only an else clause is needed to handle
    the error conditions.


Using switch

switch (day) { case 0: printf("Sunday\n"); break; case 1: printf("Monday\n"); break; case 2: printf("Tuesday\n"); break; case 3: printf("Wednesday\n"); break; case 4: printf("Thursday\n"); break; case 5: printf("Friday\n"); break; case 6: printf("Saturday\n"); break; default: printf("Error - unexpected value for day\n"); printf("Should be 0-6. Value is %d\n", day); break; }

Note:
  1. The value of day is checked once and control
    goes immediately to the correct case.
    If that case has a break statement, only the
    statements of that case are executed.
  2. Only the default is needed to handle
    the error conditions.

Lesson

Cascading ifs (if/else) are more efficient than separate ifs.
The switch is even more efficient, but can only be used for
ints or chars, not floating point numbers. It can't be used
for ranges of values either, so the switch is quite limited
in its usefulness.


CSEE | 201 | 201 F'98 | lectures | news | help

Wednesday, 16-Sep-1998 20:46:11 EDT