Table of Contents
Introduction
This program will enable the user to check whether the year entered is a leap year or not.
To understand this program, you should know about
1. C programming operators
2. C nested if…else statement
Program
#include<stdio.h> #include<math.h> int main() { int year; printf("Enter a year:"); scanf("%d",&year); if(year%400==0) //if perfectly divisible by 400, it's a leap year { printf("%d is a leap year",year); } else if(year%100==0) //if perfectly divisible by 100 but not by 400, it's not a leap year { printf("%d is a not leap year",year); } else if(year%4==0) //if perfectly divisible by 4 but not by 100, it's a leap year { printf("%d is a leap year",year); } else // neither condition written above states true, then it's not a leap year { printf("%d is a not leap year",year); } return 0; }
Output
Explanation
In the above code, 4 different statements are written using if, else if, and else. It is because the logic works in serial order as written in the above code.
The value entered by the user is 2021.
if(year%400==0) this gives false result with year=2021 thus, controls moves to next statement.
else if(year%100==0) this gives a false result again with year=2021 thus, controls move to the next statement.
else if(year%4==0) 2021 is not completely divisible by 4, thus it is false.
Thus, the else part is executed, and ‘2021 is not a leap year is the output of the last ‘else’ statement.
0 Comments