C Program to Check if a year is Leap or not

-Advertisement-

General Introduction:

If we ask most of the people what leap year is, then most of them will reply “A year in every 4 years.”. While it is partially true, it is not that simple.

4,8,12,16,20,………….,96 are leap years. However, 100 is not a leap year.
104,108,112,116,120,……..,196 are leap year. However, 200 is not a leap year.
204,208,212,216,220,…..,296 are leap years. However, 300 is not a leap year.
304,308,312,316,320,……,396 are leap years and 400 is also leap year.
And so on.

Algorithm for finding leap year:

  • Step 1: If the year is exactly divisible by 4 go to step 2, else go to step 5.
  • Step 2: If the year is exactly divisible by 100 go to step 3, else go to step 4.
  • Step 3: If the year is exactly divisible by 400, go to step 4, else go to step 5.
  • Step 4: Print the year is a leap year.
  • Step 5: Print the year is not a leap year.

Code in C:

#include<stdio.h>
#include<conio.h>
int main()
{
	int year;
	printf("Enter the year to know if it is leap or not: ");
	scanf("%d",&year);
	
	if(year%4==0)
	{
		if(year%100==0)
		{
			if(year%400==0)
			{
				printf("%d year is leap year",year);
			}
			else
			{
				printf("%d year is not leap year",year);
			}
		}
		
		else
		{
			printf("%d year is leap year.",year);
		}
	}
	
	else
	{
		printf("%d year is not leap year",year);
	}
	getch();
	return(0);
}

Optimized Code:

#include<stdio.h>
#include<conio.h>

int main()
{
	int year;
	printf("Enter the year to know if it is leap or not: ");
	scanf("%d",&year);
	
	if(year%400==0)
	{
		printf("%d year is leap year",year);
	}
	
	else if(year%100==0)
	{
		printf("%d year is not leap year",year);
	}
	
	else if(year%4==0)
	{
		printf("%d year is leap year",year);
	}
	
	else
	{
		printf("%d year is not leap year",year);
	}
	getch();
	return(0);
}

Outputs:

C Program to Check if a year is Leap or not 1
When the year is only divisible by 4.
C Program to Check if a year is Leap or not 2
When the year is not divisible by 4.
C Program to Check if a year is Leap or not 3
When the year is divisible by 4 and 100 but not by 400.
C Program to Check if a year is Leap or not 4
When the year is divisible by 4, 100 and also 400.

Also Read: C Program to Implement Binary Search

-Advertisement-

LEAVE A REPLY

Please enter your comment!
Please enter your name here