C program to check leap year using Conditional operator

C program to check leap year using Conditional operator

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.

Required knowledge

Operators, Data Types in c, Variables in C

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




Instagram