A leap year is as a year which contains one additional day to keep the calendar year synchronized with astronomical year. The leap year carries a great significance in the field of astronomical study and time. In this simple tutorial, we are going to write a C source code to Check Leap Year, and go through its algorithm and sample output of the program.
Checking leap year is a popular tutorial in C programing language to learn implementation of decision making sentences such as if(), else if(), and more. It also gives the idea of many mathematical operations that are performed in C programming along with the idea of fundamental input and output functions such as printf(), scanf(), etc.
The basic mathematical trick or methodology to check whether a year is leap year or not is division by 400, 100 and 4. If a year is divisible by 4 without generating any remainder, the year is a leap year. Also, if the year is divisible by 400, it may be leap, else not.
Algorithm to Check Leap Year:
- Start
- Declare variable (in this program there is a single variable i.e. year)
- Enter the year to check if it is a leap year or not
- Divide the year by 400.
- If the year is divisible by 400, print the year as leap year
- Otherwise, divide the year by 100
- If the year is divisible by 100, the year is not a leap year
- If the year is not divisible by 100, divide it by 4
- If the year is divisible by 4, it is a leap year
- Else, print the year is not a leap year
- Stop
Source Code to Check Leap Year using C:
#include <stdio.h>
int main()
{
int yr; // yr represents the year
printf(" Enter the year to check if it is a leap year or not: ");
scanf("%d", &yr);
if ( yr%400 == 0) // dividing by 400
printf(" %d is a leap year.\n", yr);
else if ( yr%100 == 0) // dividing by 100
printf(" %d is not a leap yr.\n", yr);
else if ( yr%4 == 0 ) // dividing by 4
printf(" %d is a leap year.\n", yr);
else
printf(" %d is not a leap year.\n", yr); // output
return 0;
}
The above C program is short, simple and easy to understand. It includes a single header file: stdio.h to include the basic input/output functions from the standard C library. When the program is executed, it asks for the year which is to be checked. Then, all the division procedures as mentioned in algorithm are performed. A sample output screenshot is presented below:
This C tutorial to check leap year is presented here to help you learn basic mathematical operations in C. The source is to be compiled in Code::Blocks IDE, and it is completely error free. If you have any queries regarding the any content of post: algorithm or source code, you can share them from the comments section.