Placement Prep

Days in a Given Month: Python, Java, C and C++ Programs

Python, Java, C, and C++ programs to find days in a given month and year. Covers the leap year rule, if-elif, array lookup, and standard library approaches.

By FACE Prep Team 7 min read
python java c-program leap-year placement-prep programming date-calculation

February is the only month whose length changes from year to year. Every other month’s length is fixed, so the real work in this problem is the three-part leap year rule.

This type of date-arithmetic question appears in placement coding rounds at TCS, Infosys, and Wipro. It tests basic conditional branching and the ability to write a helper function. This article covers four approaches: if-elif, array lookup, Python’s calendar module, and Java’s YearMonth.lengthOfMonth(), with implementations in all four common languages.

Month lengths and where February stands apart

Eleven of the twelve months have the same length every year. The complete table:

MonthNumberDays
January131
February228 or 29
March331
April430
May531
June630
July731
August831
September930
October1031
November1130
December1231

The pattern to remember: months 4, 6, 9, and 11 have 30 days. Month 2 (February) varies. Everything else is 31.

The array-based approach stores this directly:

days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

Index 0 is a placeholder so that days[1] through days[12] map directly to January through December. Index 2 stores 28 as the base value for February. The leap year check then overrides the February return when the year qualifies.

The leap year rule from first principles

The Gregorian calendar’s leap year rule corrects for the fact that an astronomical year is approximately 365.2422 days, not a whole number. Three corrections stack on top of each other:

  • Base rule: a year divisible by 4 is a leap year. This compensates for the 0.2422-day shortfall per year.
  • Century exception: century years (divisible by 100) skip the leap day. The correction overshoots slightly, so removing one leap day per century brings the calendar back on track. Years 1700, 1800, and 1900 are all non-leap years for this reason.
  • 400-year override: skipping every century year over-corrects in the other direction. So years divisible by 400 are leap years after all. The year 2000 is a leap year; 2100 will not be.

In code, the three-part rule written as a Python function:

def is_leap_year(year):
    return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)

Verified results (re-derived from the rule):

  • 2024: 2024 % 4 == 0 and 2024 % 100 != 0 — left clause True — leap year, 29 days
  • 1900: 1900 % 4 == 0 but 1900 % 100 == 0 — left clause False; 1900 % 400 != 0 — right clause False — not a leap year, 28 days
  • 2000: 2000 % 4 == 0 but 2000 % 100 == 0 — left clause False; 2000 % 400 == 0 — right clause True — leap year, 29 days

The 1900/2000 pair is the standard test case because it breaks the naive year % 4 == 0 shortcut. Any program that relies on that shortcut alone will return 29 for February 1900, which is wrong.

Python programs

Method 1: if-elif chain with is_leap() helper

def is_leap_year(year):
    return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)

def days_in_month(month, year):
    if month == 2:
        return 29 if is_leap_year(year) else 28
    elif month in [4, 6, 9, 11]:
        return 30
    elif month in [1, 3, 5, 7, 8, 10, 12]:
        return 31
    else:
        return -1  # Invalid month

month = int(input("Enter month (1-12): "))
year = int(input("Enter year: "))
days = days_in_month(month, year)
if days == -1:
    print("Invalid month")
else:
    print(f"Number of days: {days}")

Separating the leap year logic into is_leap_year() makes it easy to test independently. The days_in_month() function handles month routing with an if-elif chain: February first (the only conditional case), then the 30-day months, then the 31-day months, with a fallback for invalid input.

Method 2: array lookup

def days_in_month(month, year):
    days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    if month < 1 or month > 12:
        return -1
    if month == 2 and ((year % 4 == 0 and year % 100 != 0) or year % 400 == 0):
        return 29
    return days[month]

month = int(input("Enter month (1-12): "))
year = int(input("Enter year: "))
print(f"Number of days: {days_in_month(month, year)}")

This version inlines the leap year check rather than calling a helper. For all months except February, it returns days[month] directly from the array. For February, it evaluates the leap condition first.

Method 3: Python standard library (preferred for production)

import calendar

month = int(input("Enter month (1-12): "))
year = int(input("Enter year: "))
_, days = calendar.monthrange(year, month)
print(f"Number of days: {days}")

Python’s calendar.monthrange(year, month) returns a two-element tuple: the weekday index of the month’s first day and the total number of days. The _ discards the weekday element. This approach handles all leap year logic internally, with no manual formula needed.

C and C++ programs

C: switch-case approach

#include <stdio.h>

int is_leap(int year) {
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

int days_in_month(int month, int year) {
    switch (month) {
        case 1: case 3: case 5: case 7: case 8: case 10: case 12:
            return 31;
        case 4: case 6: case 9: case 11:
            return 30;
        case 2:
            return is_leap(year) ? 29 : 28;
        default:
            return -1;
    }
}

int main() {
    int month, year;
    printf("Enter month (1-12): ");
    scanf("%d", &month);
    printf("Enter year: ");
    scanf("%d", &year);
    int days = days_in_month(month, year);
    if (days == -1)
        printf("Invalid month\n");
    else
        printf("Number of days: %d\n", days);
    return 0;
}

C++: array lookup approach

#include <iostream>
using namespace std;

bool is_leap(int year) {
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

int days_in_month(int month, int year) {
    int days[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    if (month < 1 || month > 12) return -1;
    if (month == 2 && is_leap(year)) return 29;
    return days[month];
}

int main() {
    int month, year;
    cin >> month >> year;
    cout << "Number of days: " << days_in_month(month, year) << endl;
    return 0;
}

The C and C++ implementations use && and || in place of Python’s and and or. The switch-case in C groups multiple cases with fall-through: writing case 1: case 3: on the same line routes all seven 31-day months to a single return statement. The C++ version uses the array approach instead, which avoids the fall-through syntax.

Java programs

Method 1: switch-case with manual isLeap()

import java.util.Scanner;

public class DaysInMonth {
    static boolean isLeap(int year) {
        return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
    }

    static int daysInMonth(int month, int year) {
        switch (month) {
            case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31;
            case 4: case 6: case 9: case 11: return 30;
            case 2: return isLeap(year) ? 29 : 28;
            default: return -1;
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int month = sc.nextInt();
        int year = sc.nextInt();
        System.out.println("Number of days: " + daysInMonth(month, year));
        sc.close();
    }
}

Method 2: YearMonth.lengthOfMonth() (preferred for production)

import java.time.YearMonth;
import java.util.Scanner;

public class DaysInMonth {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int month = sc.nextInt();
        int year = sc.nextInt();
        int days = YearMonth.of(year, month).lengthOfMonth();
        System.out.println("Number of days: " + days);
        sc.close();
    }
}

YearMonth.of(year, month).lengthOfMonth() is part of the java.time package, available since Java 8. It handles all calendar edge cases internally. YearMonth.of(2000, 2).lengthOfMonth() returns 29; YearMonth.of(1900, 2).lengthOfMonth() returns 28.

Verified sample inputs and outputs

Running the four standard test cases through any of the above programs:

  • Input: month = 2, year = 2024is_leap(2024) is True (divisible by 4, not by 100) — Output: Number of days: 29
  • Input: month = 2, year = 1900is_leap(1900) is False (divisible by 100, not by 400) — Output: Number of days: 28
  • Input: month = 2, year = 2000is_leap(2000) is True (divisible by 400) — Output: Number of days: 29
  • Input: month = 3, year = 1996 — March always has 31 days, leap year check is not needed — Output: Number of days: 31

The 1900 case is the one that catches most incorrect implementations. A program that checks only year % 4 == 0 returns 29 for February 1900, which is wrong. The full three-part formula is the only one that passes all three edge cases.

For more programs using the same conditional-logic pattern, the Python example programs for practice collection covers a wide range of patterns. The Armstrong number check uses the same helper-function structure, with a digit-extraction loop in place of the leap year formula. For if-elif chain practice, greatest of three numbers in Python applies the same multi-branch pattern to comparisons.

The calendar.monthrange() approach shows why Python’s standard library is worth learning properly: one function call handles all three parts of the leap year rule, with no manual formula needed. That same instinct (reach for the library first, test with edge cases like 1900 and 2000) transfers to Python work on live APIs. TinkerLLM at ₹299 is the entry point for that next step: Python projects that call LLM APIs, where the same conditional branching and date-handling patterns from this article come up in real tool code.

Primary sources

Frequently asked questions

How do I check if a year is a leap year in Python?

Use the three-part rule: return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0). This handles the century exception — 1900 is not a leap year even though it is divisible by 4.

What does calendar.monthrange() return in Python?

It returns a two-element tuple: the weekday index of the first day (0 = Monday) and the total number of days in that month. Unpack with _, days = calendar.monthrange(year, month) to get the day count.

What does YearMonth.lengthOfMonth() return in Java?

An int representing the number of days in that specific month and year. For February in a leap year it returns 29; in a non-leap year it returns 28. No manual leap-year check is needed.

Is 1900 a leap year?

No. Although 1900 is divisible by 4, it is also divisible by 100 and not divisible by 400. Century years must be divisible by 400 to qualify. February 1900 had 28 days.

How many days does February have in a leap year?

29 days. February has 28 days in a regular year and 29 days in a leap year. A year is a leap year if it is divisible by 400, or divisible by 4 but not by 100.

Which approach should I use in a placement coding test?

Use the if-elif or switch-case approach with a manual is_leap() helper function. Placement coding platforms often restrict standard library imports, and writing the logic manually demonstrates clear conditional reasoning.

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹299 launch)
Free AI Roadmap PDF