C program to check leap year using Conditional/Ternary operator

Write a C program to enter any year and check whether year is leap year or not using conditional/ternary operator (?:).

Also view this program using if else -
C program to check leap year using if else.

Required knowledge:

Basic C programming, Conditional operator, Leap year condition

Leap year condition:

If the year is EXACTLY DIVISIBLE by 4 and NOT DIVISIBLE by 100 then its LEAP YEAR
Else if the year is EXACTLY DIVISIBLE 400 then its LEAP YEAR
Else its a COMMON YEAR

Program:

/**
 * C program to check leap year using conditional operator
 */

#include <stdio.h>

int main()
{
    int year;
 
    /*
     * Reads year from user
     */
    printf("Enter any year: ");
    scanf("%d", &year);

    (year%4==0 && year%100!=0) ? printf("LEAP YEAR") :
        (year%400 ==0 ) ? printf("LEAP YEAR") : printf("COMMON YEAR");

    return 0;
} 

Note: We can also write the same program using conditional operator as:

/**
 * C program to check leap year using conditional operator
 */

#include <stdio.h>

int main()
{
    int year;
 
    /*
     * Reads 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
X
_
Enter any year: 2016

LEAP YEAR

Happy coding ;)


You may also like

Labels: , ,