LearnFrenzy
Sign in Take a free test

Control Instructions · Decision Making Programs · Question 7

Validate a date (day, month, year) in C Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

Check whether a day/month/year combination is a real calendar date, including leap years.

Solution
main.c
#include <stdbool.h>
#include <stdio.h>

bool valid_date(int d, int m, int y) {
    if (y < 1 || m < 1 || m > 12 || d < 1)
        return false;
    int max;
    switch (m) {
    case 2:
        max = ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0) ? 29 : 28;
        break;
    case 4: case 6: case 9: case 11:
        max = 30;
        break;
    default:
        max = 31;
    }
    return d <= max;
}

int main(void) {
    int dates[][3] = {{29, 2, 2024}, {29, 2, 2026}, {31, 4, 2026}, {31, 12, 2026}};
    for (int i = 0; i < 4; i++)
        printf("%02d/%02d/%d: %s\n", dates[i][0], dates[i][1], dates[i][2],
               valid_date(dates[i][0], dates[i][1], dates[i][2]) ? "valid" : "invalid");
    return 0;
}

Output Verified by compiling and running

29/02/2024: valid
29/02/2026: invalid
31/04/2026: invalid
31/12/2026: valid

Simple range checks come first as guards; the switch then finds the month length, with February using the leap-year rule. Every month falls into exactly one case.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links