• 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.


  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int main(){
  5.     
  6.     int year;
  7.     printf("Enter a year to check if it is a leap year or not \n");
  8.     scanf("%d", &year);
  9.  
  10.    
  11.     (year%4==0 && year%100!=0) ? printf("Leap Year") :
  12.         (year%400 ==0 ) ? printf("Leap Year") : printf("not a leap year");
  13.         
  14.    getch();
  15.     
  16. }

Output:


  1. Enter a year to check if it is a leap year or not
  2. 2012
  3. Leap Year


leap year in c conditional operator

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.

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu