C Program to Check a Leap Year
Programming question to check a leap year.
Programming question to check a leap year.
Write a program to check whether a given year is a leap year or not according to the Gregorian Calendar System.
Input:
Enter the year: 2024
Output:
It's a leap year.
Explanation:
Year 2024 is a leap year because it is perfectly divisible by 4.
Input:
Enter the year: 2021
Output:
It's not a leap year.
Explanation:
Year 2021 was not a leap year because it is not divisible by 4.
Input:
Enter the year: 2100
Output:
It's not a leap year.
Explanation:
Year 2100 is not a leap year because it is divisible by 100 but not divisible by 400.
You need to write the complete program using the following template as the starter:
#include <stdio.h>
int main() {
int year;
// The prompt.
printf("Enter the year: ");
scanf("%d", &year);
// Write your code here.
return 0;
}
Copy and paste the above code in your favorite IDE and start writing your code after the comment // Write your code here.
Pro tip: First, try writing the code on your own. Try every possible thing you can to come up with the solution. If you still can’t figure it out, then check the solution and see what went wrong. This is how you learn. 🙂
To verify the program you have written, go ahead and test your program using the following test cases:
Input | Output | |
---|---|---|
Test Case 1 | 2000 | It’s a leap year. |
Test Case 2 | 1 | It’s not a leap year. |
Test Case 3 | 300 | It’s not a leap year. |
Test Case 4 | 400 | It’s a leap year. |
Don’t forget to try the code on your own before diving into the solution.
Note that we’re assuming the user will only enter positive values for the year.
Following are the multiple approaches to the same problem:
We can use Nested if-else to check multiple conditions as shown in the following code:
#include <stdio.h>
int main() {
int year;
// The prompt.
printf("Enter the year: ");
scanf("%d", &year);
// Write your code here.
if (year % 4 == 0) {
if (year % 100 != 0) {
printf("It's a leap year.\n");
} else {
if (year % 400 == 0) {
printf("It's a leap year.\n");
} else {
printf("It's not a leap year.\n");
}
}
} else {
printf("It's not a leap year.\n");
}
return 0;
}
Output:
Enter the year: 2000
It's a leap year.
You can check the above program for multiple test cases and the code works just fine.
The previous program can easily be rewritten using the logical conditions as follows:
#include <stdio.h>
int main() {
int year;
// The prompt.
printf("Enter a year: ");
scanf("%d", &year);
// Write your code here.
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
printf("It's a leap year");
} else {
printf("It's not a leap year");
}
return 0;
}
Output:
Enter a year: 2022
It's not a leap year
Leave a comment