C program to check leap year
C program to check leap year:
Write a C program to input year from user and check whether a given year is a leap year or not using if...else. Let's see the below step by step logic to check whether a given year is a leap year or not.
Example:
- INPUT
- Enter year to check leap year: 2020
OUTPUT
2020 is a leap year.
Required knowledge for this exercise
Logic to check whether a given year is a leap year or not:
Leap year is a special year that contains an extra day (extra day is also known as leap day), that extra day is added to the end of the month, February. Therefore, February has 29 days instead of 28 days and leap year has 366 days instead of common 365 days. Leap years occur on every four years.
Now let's see the below step by step logic to check divisibility of a number.
1) Input a year from user and store it in variable year
using scanf() function.
2) Check if year
is exactly divisible by 4
but not divisible by 100
then, it is a leap year. OR if year
is exactly divisible by 400
then,
that year is also a leap year.
Program to check leap year using if...else statement:
For Example:
- /* C Program to check whether given year is a leap year or not. */
#include <stdio.h>
int main()
{
int year;
/* Input a year from user */
printf("Enter a year: ");
scanf("%d", &year);
/*
* If any year is divisible by 4 but not divisible by 100,
* then it is a leap year or if year is divisible by 400,
* then it is also a leap year. see below algorithm
*/
if(((year % 4 == 0) && (year % 100 !=0)) || (year % 400==0))
{
printf("Yes! %d is a leap year", year);
}
else
{
printf("NO! %d is not a leap year %d", year);
}
return 0;
}
Note: As you can see in above programif
orelse
body contains only single statement. Hence, you can ignore braces {
}
after if
andelse
statement.
For Example:
- if(((year % 4 == 0) && (year % 100 !=0)) || (year % 400==0))
printf("Yes! %d is a leap year", year);
else
printf("NO! %d is not a leap year %d", year);
Output:
- Enter year to check leap year: 2020
- Yes! 2020 is a leap year.
- Enter year to check leap year: 2003
- No! 2003 is not a leap year.
Help others by sharing this page.
Ahmad Irshad
Author & Editor
I love blogging, teaching, learning computer science and sharing it to others. I've written and develped this site so that students may learn computer science related tutorials eaisly. MCA / MCITP
Thursday, July 23, 2020
C
0 Comments:
Post a Comment
Please don't enter any spam link in the comment box.