CS 102
Assignment 5
due Thursday 17 February at 01:00 AM
Table of Contents
1 Description
Write a program that will:
- Ask the user for a month (input as an integer 1–12).
- Ask the user for a day of the month.
- Give an error message if month is out of range.
- Give an error message if day is out of range for that month (such as April 31st).
- IF there are no errors, then print out the date using the full name of the month, such as “March 25th”.
Here are a few sample runs of the program, but it should work for other numbers as well.
Enter month (1-12): 3 Enter day of month: 25 March 25th
Enter month (1-12): 0 ERROR: invalid month
Enter month (1-12): 4 Enter day of month: 31 ERROR: invalid day
Enter month (1-12): 12 Enter day of month: 0 ERROR: invalid day
Enter month (1-12): 11 Enter day of month: 23 November 23rd
2 Tips
Some tips, for getting full credit:
- Make sure you use appropriate indentation and alignment of braces.
- Include a comment at the top with your name and the date.
Some code fragments from class, that may be useful:
switch(month)
{
case 1:
printf("January");
break;
case 2:
printf("February");
break;
}
switch(month)
{
case 2:
num_days = 28;
break;
case 4:
case 6:
case 9:
case 11:
num_days = 30;
break;
default:
num_days = 31;
}
3 Solution
Here is a complete solution that we explored in class on 17 February.
#include <stdio.h>
int main()
{
int month, day, num_days;
printf("Enter month (1-12): ");
scanf("%d", &month);
if(month > 12 || month < 1)
{
printf("ERROR: Invalid month\n");
return 0;
}
switch(month)
{
case 2:
num_days = 28;
break;
case 4: case 11: case 6: case 9:
num_days = 30;
break;
default:
num_days = 31;
}
printf("Enter day (1-%d): ", num_days);
scanf("%d", &day);
if(day < 1 || day > num_days)
{
printf("ERROR: Invalid day\n");
return 0;
}
switch(month)
{
case 1: printf("January "); break;
case 2: printf("February "); break;
case 3: printf("March "); break;
case 4: printf("April "); break;
case 5: printf("May "); break;
case 6: printf("June "); break;
case 7: printf("July "); break;
case 8: printf("August "); break;
case 9: printf("September "); break;
case 10: printf("October "); break;
case 11: printf("November "); break;
case 12: printf("December "); break;
}
printf("%d", day);
switch(day)
{
case 1: case 21: case 31: printf("st\n"); break;
case 2: case 22: printf("nd\n"); break;
case 3: case 23: printf("rd\n"); break;
default: printf("th\n");
}
return 0;
}