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

C program to check leap year using Conditional/Ternary operator



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

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 yea
r is EXACTLY DIVISIBLE 400 then its LEAP YEAR 
Else its a COMMON YEAR 

Program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
 * 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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
 * 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
Enter any year: 2016

LEAP YEAR


Comments

Most Viewed

WAP to input week number and print week day name.

C Program to Find Third Angle of a Triangle