In this tutorial, we will learn to write a C program to validate a given date. For example, if the user enters a date 31/02/2020 (where 02 is a month) then the program should be able to tell that its an invalid date.
C Program to validate date
Let’s write the complete code for the date verification. The explanation of the program is provided at the end of the code along with the output.
#include <stdio.h>
#include <stdbool.h>
// Define a structure to represent date
struct Date {
int day;
int month;
int year;
};
// Function to check if a given year is a leap year
bool isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
// Function to validate a date
bool isValidDate(struct Date date) {
// the 1st element represents the number of days in January,
// second for Feb and so on, the last element represents days in Dec
int daysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// Check if year is valid (greater than 0)
if (date.year <= 0)
return false;
// Check if month is between 1 and 12
if (date.month < 1 || date.month > 12)
return false;
// Check for February in case of leap year
if (date.month == 2 && isLeapYear(date.year)) {
if (date.day < 1 || date.day > 29)
return false;
}
else {
// Check if day is within the range for the given month
if (date.day < 1 || date.day > daysInMonth[date.month - 1])
return false;
}
// If all conditions are met, the date is valid
return true;
}
int main() {
struct Date date;
// Input the date
printf("Enter date (DD/MM/YYYY): ");
scanf("%d/%d/%d", &date.day, &date.month, &date.year);
// Check if the date is valid and print the result
if (isValidDate(date)) {
printf("Valid date!\n");
} else {
printf("Invalid date!\n");
}
return 0;
}
Explanation:
- Structure Definition:
- We define a structure named
Date
to hold day, month, and year. This is where we store the input date and the structure variabledate
is used for the validity check process in the program.
- We define a structure named
- Leap Year Check:
- We have a function
isLeapYear()
to check if a given year is a leap year. This will make sure that a 29 days feb is valid date for leap years but not for normal years.
- We have a function
- Validation Function:
- The function
isValidDate()
checks if the given date is valid. - It validates the year, month, and day based on the rules of the Gregorian calendar.
- It considers leap years for February.
- The function
- Main Function:
- It prompts the user to input a date in the format
DD/MM/YYYY
. - It calls the
isValidDate()
function to check if the date is valid. - It prints whether the date is valid or invalid based on the return value of
isValidDate()
.
- It prompts the user to input a date in the format
Output:
Output 1:
Enter date (DD/MM/YYYY): 29/02/2024
Valid date!
Output 2:
Enter date (DD/MM/YYYY): 31/04/2021
Invalid date!
Output 3:
Enter date (DD/MM/YYYY): 30/02/2022
Invalid date!
Leave a Reply