- We have already seen how to check leap year or not using C program here
- Now we need to find out a leap year by using conditional operator using C programming language.
- expression ? value1 : value2
- if expression is true then it picks value1 else value2.
- Let us see an example C program to check a year is leap year or not by using conditional operator.
Program #1: Write a C program to find leap year using conditional operator without using any function and loops.
- #include <stdio.h>
- #include <stdlib.h>
- int main(){
- int year;
- printf("Enter a year to check if it is a leap year or not \n");
- scanf("%d", &year);
- (year%4==0 && year%100!=0) ? printf("Leap Year") :
- (year%400 ==0 ) ? printf("Leap Year") : printf("not a leap year");
- getch();
- }
Output:
- Enter a year to check if it is a leap year or not
- 2012
- Leap Year
this program prompts the user to enter a year and then uses the conditional operator to check if the year is a leap year. The condition being checked is whether the year is evenly divisible by 4 and not divisible by 100, or if it is evenly divisible by 400. If the year is a leap year, the program will print "year is a leap year.", otherwise it will print "year is not a leap year."
The conditional operator is represented by the ? symbol. It takes three operands: a condition, an expression to execute if the condition is true, and an expression to execute if the condition is false.
In this example, the condition is (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0), the first expression to execute if the condition is true is printf("%d is a leap year.\n", year) and the second expression if the condition is false is printf("%d is not a leap year.\n", year)
It's important to note that this program doesn't take into account the Julian calendar and leap year rules before the Gregorian calendar.
In summary, this is a simple C program that uses the conditional operator to check if a year is a leap year, by evaluating a condition that checks if the year is evenly divisible by 4 and not divisible by 100, or if it is evenly divisible by 400. The program uses the ternary operator to make the code more concise and readable.
No comments