Check Leap Year Using Ternary Operator in C
In this tutorial, we will write a C program to check whether a given year is a leap year or not using the ternary (conditional) operator.
Leap Year Rule
A year is a leap year if:
- It is divisible by 4 AND not divisible by 100
- OR it is divisible by 400
Mathematical Condition:
(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
C Program
#include <stdio.h>
int main() {
int year;
printf("Enter a year: ");
scanf("%d", &year);
// Using ternary operator
( (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) )
? printf("%d is a Leap Year.\n", year)
: printf("%d is NOT a Leap Year.\n", year);
return 0;
}
Explanation
Step 1: Input
The program takes a year as input from the user.
Step 2: Condition Check
(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
year % 4 == 0→ Divisible by 4year % 100 != 0→ Not divisible by 100year % 400 == 0→ Divisible by 400
Step 3: Ternary Operator
If the condition is true, it prints that the year is a Leap Year. Otherwise, it prints that it is NOT a Leap Year.
Sample Input
Enter a year: 2024
Output
2024 is a Leap Year.
Time Complexity
The program performs a constant number of operations. Therefore, the time complexity is O(1).
কোন মন্তব্য নেই:
একটি মন্তব্য পোস্ট করুন