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:
- We include the <stdio.h> header file to use printf and scanf functions.
- In the main function, we declare an integer variable year to store the user input.
- We prompt the user to enter a year using printf.
- We read the user input using scanf and store it in the variable year.
- We use an if-else statement to check if the year is a leap year or not.
- 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.
- If the condition is true, we print that the year is a leap year.
- If the condition is false, we print that the year is not a leap year.
- 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.