Write a C program to input a year and check whether year is leap year or not using conditional/ternary operator ?:
. How to check leap year using conditional operator in C programming.
Example
Input
Input year: 2016
Output
2016 is Leap Year
Required knowledge
Basic C programming, Conditional operator, Logical operators
Learn more – Program to check leap year using if…else
Leap year condition
If a year is exactly divisible by 4 and not divisible by 100 then its Leap year.
Else if year is exactly divisible 400 then its Leap year.
Else its a Common year.
Program to check leap year
/**
* C program to check leap year using conditional operator
*/
#include <stdio.h>
int main()
{
int year;
/*
* Input year from user
*/
printf("Enter any year: ");
scanf("%d", &year);
/*
* If year%4==0 and year%100==0 then
* print leap year
* else if year%400==0 then
* print leap year
* else
* print common year
*/
(year%4==0 && year%100!=0) ? printf("LEAP YEAR") :
(year%400 ==0 ) ? printf("LEAP YEAR") : printf("COMMON YEAR");
return 0;
}
Note: Another approach of writing the same program.
/**
* C program to check leap year using conditional operator
*/
#include <stdio.h>
int main()
{
int year;
/*
* Input year from user
*/
printf("Enter any year: ");
scanf("%d", &year);
printf("%s", ((year%4==0 && year%100!=0) ?
"LEAP YEAR" : (year%400 ==0 ) ?
"LEAP YEAR" : "COMMON YEAR"));
return 0;
}
Output
Enter any year: 2016 LEAP YEAR
Happy coding 😉
Recommended posts
- Conditional operator programming exercises index.
- C program to find maximum between two numbers using conditional operator.
- C program to find maximum between three numbers using conditional operator.
- C program to check even or odd number using conditional operator.
- C program to check alphabet using conditional operator.