UMBC CS 201, Fall 05
 UMBC CMSC 201 Fall '05 CSEE | 201 | 201 F'05 | lectures | news | help Search Notes:

# Efficiency

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: The value of day must be checked at every if, whether or not the day has been matched and printed. A complex test is necessary to handle an error and print the error message.

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); }

### 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; }

## 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'05 | lectures | news | help

Sunday, 21-Aug-2005 09:53:21 EDT