This document provides a program to check if a given date is valid or not. It first describes the objectives, related knowledge on leap years, and the problem statement. It then outlines the analysis and suggests an algorithm to accept date input, check if it is valid using a validDate function, and print the output. The validDate function uses logic to check the date values against maximum days per month and leap year rules to return true or false. The exercise provides the C code to implement this program, including the validDate function and main function to test a sample date.
Download as DOCX, PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
25 views
Exercise 2:: Program 2
This document provides a program to check if a given date is valid or not. It first describes the objectives, related knowledge on leap years, and the problem statement. It then outlines the analysis and suggests an algorithm to accept date input, check if it is valid using a validDate function, and print the output. The validDate function uses logic to check the date values against maximum days per month and leap year rules to return true or false. The exercise provides the C code to implement this program, including the validDate function and main function to test a sample date.
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2
Program 2:
Objectives Practice implementing simple functions
Related knowledge Leap year (y): (y%400==0 || ( y%4==0 && y%100!=0)) Problem Write a C program that will accept data of a day then print out whether they are valid or not. Analysis Suggested algorithm (logical order of verbs) Data of a day Begin int d, m, y Accept d, m, y If (valid(d,m,y)) print out “valid date” Else print out “invalid date” End Algorithm for int validDate ( int d, int m, int y) { checking whether int maxd = 31; /*max day of months 1, 3, 5, 7, 8, 10, 12 a date is valid or */ not /* basic checking */ if ( d<1 || d>31 || m<1 || m>12) return 0; /* update maxd of a month */ if ( m==4 || m==6 || m==9 || m=11) maxd=30; else if (m==2) { /* leap year? */ if ( y%400==0 || ( y%4==0 && y%100!=0) maxd=29; else maxd=28; } return d<=maxd; }
Exercise 2: #include<stdio.h>
int validDate (int d, int m, int y){
int maxd=31;
if(d <1 || d> 31 || m<1 || m >12) return 0 ;
if( m ==4 || m == 6 || m ==9 || m == 11) maxd = 30;
else if(m==2) {
if ( y%400==0 || y%4==0 && y%100!=0 ) maxd=29;
else maxd=28;
return d<=maxd;
int main(){ int d, m , y ;
printf("Enter the day: "); scanf("%d", &d);
printf("Enter the month: "); scanf("%d", &m);
printf("Enter the year: "); scanf("%d", &y);
if (validDate(d, m, y)==1) {
printf ("The date of %d/%d/%d is a valid date!\n", d, m ,y);
}else
printf("The date of %d/%d/%d is not a valid date!\n", d, m ,y);