C Program to check leap year using Ternary Operator

In this C tutorial we are going to check wheather the Year inputted by the user is a Leap year or not. We can do it in numerous methods but in this tutorial we’re focusing on writing C program to check leap year using Ternary operator.

Program Outline

In this C program, first we’ll take a year as a input from the user and save it in a variable say Year and then by using Conditional operator/Ternary operator we’ll be able to evaluate wheather the inputted year is Leap year or not.

Concept

Before writing this C Program to check leap year using Ternary Operator. You need to learn few concepts before writing this program which are –

  • What is a leap year ?

A leap year is exactly divisible by 4 except for century years (years ending with 00). The century year is a leap year only if it is perfectly divisible by 400.

  • What is Ternary operator/Conditional operator?

The conditional operator is kind of similar to the if-else statement as it does follow the same algorithm as of if-else statement but the conditional operator takes less space and helps to write the if-else statements in the shortest way possible.

Syntax of Ternary operator
variable = Expression1 ? Expression2 : Expression3

Program

After understanding the basic concept required to write this program now let’s begin with the main part and start writing code-

#include <stdio.h>
int main()
{
    int year;
  
    /*
     * Input 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;
}

Output

After writing the C Program to check leap year using Ternary Operator. Let’s check the output what we are getting. As we inputted year as “2022” let’s see what output it gives.

C Program to check leap year using Ternary Operator

As you can see we are getting output of “Common year ” so our program is working perfectly because 2022 is not a leap year.

groot
groot

Leave a Reply

Your email address will not be published. Required fields are marked *