In: Computer Science
Question 1: Write a C program that reads a date from the keyboard and tests whether it contains a valid date. Display the date and a message that indicates whether it is valid. If it is not valid, also display a message explaining why it is not valid. The input date will have the format:
mm/dd/yyyy
Note that there is no space in the above format. A date in this format must be entered in one line.
A valid month value mm must be from 01 to 12 ( January is 01). The day value dd must be from 01 to a value that is appropriate for the given month. September, April, June, and November each have 30 days. February has 28 days except for leap years when it has 29. The remaining months all have 31 days each. For the sake of simplicity assume the year is a leap year.
Note: It is an error if the user enters any other character in place of: /.
Hints:
Your program can read a date with one scanf and 3 variables.
#include<stdio.h>
int main()
{
int date,month,year;
printf("Enter date (MM/DD/YYYY format): ");
scanf("%d/%d/%d",&month,&date,&year);
if(month>=1 && month<=12)
{
if((date>=1 && date<=31) && (month==1 ||
month==3 || month==5 || month==7 || month==8 || month==10 ||
month==12))//remaining months
printf("Date is valid.\n");
else if((date>=1 && date<=30) && (month==4 ||
month==6 || month==9 || month==11))// September, April, June, and
November each have 30 days.
printf("Date is valid.\n");
else if((date>=1 && date<=29) &&
(month==2))//For the sake of simplicity assume the year is a leap
year. so 29 days for feb
printf("Date is valid.\n");
else
printf("Date is invalid.\n");
}
else
printf("Month is not valid.\n");
return 0;
}