Check if a Year is a Leap Year - C Program
Check if a Year is a Leap Year - C Program
This blog post demonstrates a C program to determine whether a given year is a leap year or not. A leap year is divisible by 4, but if it is divisible by 100, it must also be divisible by 400.
Program Code
#include <stdio.h>
// Function to check if a year is a leap year
int isLeapYear(int year) {
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
return 1; // Leap year
} else {
return 0; // Not a leap year
}
}
int main() {
int year;
// Prompt user for input
printf("Enter a year: ");
scanf("%d", &year);
// Check if the year is a leap year
if (isLeapYear(year)) {
printf("%d is a leap year.\n", year);
} else {
printf("%d is not a leap year.\n", year);
}
return 0;
}
Explanation
This program performs the following steps:
- Include the Standard I/O Library: The program includes the
<stdio.h>
library for input and output operations. - Define Leap Year Function: The
isLeapYear()
function checks if a year is a leap year using the rules: divisible by 4 but not by 100, unless divisible by 400. - Read User Input: The program reads an integer year from the user.
- Check Leap Year: It uses the
isLeapYear()
function to determine if the year is a leap year and prints the result.
This program effectively demonstrates basic condition checks and modular programming in C.
Comments
Post a Comment