Wednesday, July 13, 2011

calculating leap year in c using if else

Most new students get really confused when it comes to calculating Leap year in C. It is given as an exercise to enhance their knowledge about using if else usages. This can be calculated using Logical operators too. But using if else provides clearer ways to calculate it. Both of the methods can be implemented in C/C++ program. Here we will discuss the if else method in C/C++


Leap year : A year is Leap year if
  1. It is not a century and gets divided by 4.
  2. It is a century and gets divided by 400.
it is clear that a year will either be century (like 1600,1700,1800,1900) or it will not be a century (like 1988,1999 etc). You get the picture right.
So the first step is to check if the given year is a century or not? it can be easily checked using modulus operator % . (Modulus operator calculates remainder) . So if the modulus gives us 0, that means the given number is divided exactly.
So 1700,1800,1900 are not Leap Years (as they all are centuries but not divided by 400).
Years like 1600,2000,2400 are Leap Years (they all are divided exactly vy 400).
On the other hand Years like 1946,1950,1950 are not Leap year (they are not centuries and are not divided exactly by 4).
While years like 1944,1948,1952 are Leap years (as they are not centuries and are divided by 4 exactly ).
How can we calculate leap year in c/ c++? well its easy:


Program:


#include<stdio.h>
int leapyear(int);// protyping function

int main()
{
    int x;
    printf("Enter a number=");
    scanf("%d",&x);
    if(leapyear(x))
    {
        printf("The %d year is Leap year",x);
    }
    else
    {
        printf("The %d year is not Leap year",x);
    }
}
int leapyear(int year)
{
    int iscentury=0;// to test if year is century or not
    if(year%100==0)
    {
        iscentury=1;//yes its a century
    }
    if(iscentury)
    {
        if(year%400==0)//century must be divided by 400
        {
            //yes?
            return(1);// you have leap year... return 1
        }
        else
        {
            return(0);// no leap year return 0
        }
    }
    else
    {
        if(year%4==0)// normal year must be divided by 4
        {
            return(1);// you have leap year return 1;    
        }
        else
        {
            return(0);// you don't have leap year return 0
        }       
    }  
}
The above C program returns 1 if it finds a Leap year otherwise returns 0 if it doesn't. easy right?

3 comments:

  1. Thank you very much . This really helped me. Ranveer

    ReplyDelete
  2. I want to print all leap year between 2000 and 1900
    can u help me to get that source code

    ReplyDelete
  3. sir can u gibe me a code 4 c++ code for leap year

    ReplyDelete