Question 2
Back to Exercise
Return the full month name for 1–12 and "invalid" otherwise, using read-only data.
Solution
#include <stdio.h>
const char *month(int m) {
static const char *const names[] = {"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"};
if (m < 1 || m > 12)
return "invalid";
return names[m - 1];
}
int main(void) {
int tests[] = {1, 8, 12, 0};
for (int i = 0; i < 4; i++)
printf("%d: %s\n", tests[i], month(tests[i]));
return 0;
}
1: January 8: August 12: December 0: invalid
The range check guards the table index. Returning const char * stops callers from writing into the shared strings.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!