Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors

Program determines it is a leap year or not

Write a program that takes a year as input and determines whether it is a leap year or not.

Program in C

C
#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.\n", year);
    } else {
        printf("%d is not a leap year.\n", year);
    }

    return 0;
}

Explanation:

  1. We include the <stdio.h> header file to use printf and scanf functions.
  2. In the main function, we declare an integer variable year to store the user input.
  3. We prompt the user to enter a year using printf.
  4. We read the user input using scanf and store it in the variable year.
  5. We use an if-else statement to check if the year is a leap year or not.
  6. The condition (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 checks whether the year is divisible by 4 but not by 100, or if it is divisible by 400. These are the conditions for a leap year.
  7. If the condition is true, we print that the year is a leap year.
  8. If the condition is false, we print that the year is not a leap year.
  9. Finally, we return 0 to indicate successful execution of the program.

Output:

Output
Enter a year: 2020
2020 is a leap year.

Program in Java

Java
import java.util.Scanner;

public class LeapYearChecker {
    public static void main(String[] args) {
        int year;

        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a year: ");
        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.");
        }

        scanner.close();
    }
}

Explanation:

Java
Enter a year: 2022
2022 is not a leap year.