C Program: Leap Year

A year is a leap year if it is divisible by 4 but not by 100, with the exception that all years divisible by 400 are leap years.

The years 1904, 1908, 1912, 1916, 1920, 1924, 1928, 1932, 1936, 1940, 1944, 1948, 1952, 1956, 1960, 1964, 1968, 1972, 1976, 1980, 1984, 1988, 1992, 1996, 2000, 2004, 2008, 2012, 2016, 2020, etc are all leap years as each of them is either divisible by 4 and not by 100 or divisible by 400.

c program leap year

To implement the above conditions, we make use of the modulo operator %, which produces the remainder when $x$ is divided by $y$. So if $x$ is divisible by $y$, the operation $x % y$ yields $0$.

Here is the C program which checks if a given year is a leap year or not.

				
				#include <stdio.h>
				 
				int main() {
					unsigned short year;

				    printf("Year: ");
				    scanf("%hu", &year);

				    if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
				    	printf("%hu is a leap year", year);
				    else 
				    	printf("%hu is not a leap year", year);
				    
				    printf("\n");

					return 0;
				}
				
			

On executing the program, the prompt to enter Year will appear. Enter some year, say 2020, and check.

				
					$ ./a.out
					Year: 2020
				
			

The program prints that the year 2020 is a leap year.

c program leap year 2020