Showing posts with label algorithm. Show all posts
Showing posts with label algorithm. Show all posts

C language program code for Leap Year

C & C++ teachers in a lot of schools use leap year calculation program as a classic example to demonstrate the nested if-else conditional scenarios of these languages.

The algorithm or logic for Leap year is basically that:
1. A year is a leap year if it is divisible by 4 but not by 100.
2. If a year is divisible by both 4 and by 100, then it can only be a leap year if it is also divisible by 400.

  • Going by the above logic, any year that is divisible by 400 must definitely be a leap year (because any number divisible by 400, is also divisible by 4)
  • If a number is not divisible by 400, then we can check whether it is divisible by 100. If that is the case then it is definitely not a leap year (even if it is divisible by 4. this is as per condition no.1 above)
  • After checking divisibility of the year by 400, and 100, lastly we can check whether the number is exactly divisible by 4. If it is, then its a leap year, else its not a leap year.
  
A simple C / C++ programming code that uses this logic for determining whether a year is a Leap year or not is given below:

#include<stdio.h>
#include<conio.h>
void main()
{
 int year;
 clrscr();
 printf("Enter the Year that you want to check : ");
 scanf("%d", &year);
  
 if(year % 400 == 0)
     printf("%d is a Leap Year.", year);
else
     if(year % 100 == 0)
         printf("%d is not a Leap Year.", year); 
    else
         if(year % 4 == 0)
              printf("%d is a Leap Year.", year);
         else
              printf("%d is not a Leap Year", year); 
              printf("\nPress any key to Quit...");
              getch();
}