Python/C/C++/JAVA

Basic Practice Programs with Code and Concept

By D.S

Check Leap Year

In this example, we're going to be discussing how to determine whether a given year is a leap year or not using various programming languages. A leap year is a year that is divisible by 4 but not divisible by 100 unless it is also divisible by 400. We'll explore different approaches to implement this logic in C, C++, Python, and Java.

(a.) C Code

#include <stdio.h>

    int main() {
        int year;

        printf("Enter a year: ");
        scanf("%d", &year);

        if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
            printf("%d is a leap year.
", year);
        } else {
            printf("%d is not a leap year.
", year);
        }

        return 0;
    }
Output:-
Enter a year: 2024
2024 is a leap year.

(b.) C++ Code

#include <iostream>

    using namespace std;

    int main() {
        int year;

        cout << "Enter a year: ";
        cin >> year;

        if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
            cout << year << " is a leap year." << endl;
        } else {
            cout << year << " is not a leap year." << endl;
        }

        return 0;
    }
Output:-
Enter a year: 2024
2024 is a leap year.

(c.) Python Code

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

    year = int(input("Enter a year: "))
    if is_leap_year(year):
        print(year, "is a leap year.")
    else:
        print(year, "is not a leap year.")
Output:-
Enter a year: 2024
2024 is a leap year.

(d.) Java Code

import java.util.Scanner;

    public class LeapYearChecker {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            System.out.print("Enter a year: ");
            int year = scanner.nextInt();

            if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
                System.out.println(year + " is a leap year.");
            } else {
                System.out.println(year + " is not a leap year.");
            }
        }
    }
Output:-
Enter a year: 2024
2024 is a leap year.