Solution for Exercise 16-10
ex1610
#include <stdio.h> int main() { enum { SUN, MON, TUE, WED, THU, FRI, SAT }; int day; printf("Enter a weekday number, 0 - 6: "); scanf("%d",&day); if( day < 0 || day > 6 ) { puts("Invalid input"); } else { switch(day) { case SUN: puts("Sunday"); break; case MON: puts("Monday"); break; case TUE: puts("Tuesday"); break; case WED: puts("Wednesday"); break; case THU: puts("Thursday"); break; case FRI: puts("Friday"); break; case SAT: puts("Saturday"); }; } return(0); }
Output
Enter a weekday number:, 0 - 6: 4
Thursday
Notes
* I used all caps for my enumerated constants, declared at Line 5. You could use lower case and you could have even specified the full day name.
* What the enumerated constants do here is make the case statements more readable.
* A final break in the case SAT:
block isn't required because the if test (Line 11) eliminates any other possibilities. Similarly, a default part of the structure isn't necessary.
Copyright © 1997-2024 by QPBC.
All rights reserved