If you have any query feel free to chat us!
Happy Coding! Happy Learning!
A leap year is a year that is divisible by 4, except for end-of-century years which must be divisible by 400.
Here is an example of a C program that checks if a year is a leap year:
Copy code
#include <stdio.h>
int main() {
int year;
printf("Enter a year: ");
scanf("%d", &year);
if (year % 4 == 0) {
if (year % 100 == 0) {
if (year % 400 == 0) {
printf("%d is a leap year.", year);
} else {
printf("%d is not a leap year.", year);
}
} else {
printf("%d is a leap year.", year);
}
} else {
printf("%d is not a leap year.", year);
}
return 0;
}
In this example, the program prompts the user to enter a year, which is stored in the variable "year". The program then uses three nested if-else statements to check if the year is a leap year. The first if statement checks if the year is divisible by 4. If the year is divisible by 4, the second if statement checks if the year is divisible by 100. If the year is divisible by 100, the third if statement checks if the year is divisible by 400. If the year is divisible by 400, it is a leap year and the program prints "year is a leap year." If the year is not divisible by 400, it is not a leap year and the program prints "year is not a leap year." If the year is not divisible by 100, it is a leap year and the program prints "year is a leap year." if the year is not divisible by 4, it is not a leap year and the program prints "year is not a leap year."
You can also use the ternary operator to check if a year is a leap year:
Copy code
printf("%d is%s a leap year.", year, (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? "" : " not");
This uses the ternary operator (also called the conditional operator) which is a shorthand for an if-else statement. It has the form condition ? expression_if_true : expression_if_false
and will return the value of expression_if_true
if condition
is true or expression_if_false
if condition
is false.
It checks if a year is divisible by 4, but not divisible by 100, or divisible by 400.
Comments: 0