• Register
94,340 points
11 6 5

Leap year in C

posted Oct 1, 2020

In this post we are going to see how to know if a year is a leap year, using the C language. That is, given a number that represents a year, indicate whether or not it is a leap.
Table of contents:

  • Function
  • Know if it is a leap year in C

Function:
Everything is based on the number and others that divide it. A year is said to be a leap year if it is divisible by 4, and (NOT divisible by 100, or divisible by 400).

The modulo ( %) operator is used to obtain the remainder of the division. It is said that a number is divisible by another when the remainder is 0. So the function looks like this:

int  isBisiesto ( long year)
{
    // Divisible by 4, and (NOT divisible by 100 or divisible by 400)
    return year% 4 == 0 && (year% 100 ! = 0 || year% 400 == 0 );
}

Know if it is a leap year in C:
In the case of the previous function, we only have to send it a year and it will tell us if it is a leap or not. Here I leave the complete code to use the function. In this case, the user is asked for a year and it is printed if it is a leap.In addition to that, a for loop is also made to print all the leap years in a period of time.

# Include  < stdio.h >

// https://parzibyte.me/blog

int  isBisiesto ( long year)
{
    // Divisible by 4, and (NOT divisible by 100 or divisible by 400)
    return year% 4 == 0 && (year% 100 ! = 0 || year% 400 == 0 );
}

int  main ()
{
    long year;
    // Small use:
    printf ( " Enter a year: " );
    scanf ( " % ld " , & year);
    int result = isSet (year);
    if (result)
    {
        printf ( " It is leap \ n " );
    }
    else
    {
        printf ( " is NOT leap \ n " );
    }
    printf ( " Now printing leaps from 1900 to 2200 \ n " );
    // And now we print the leaps from 1900 to 2200
    for (year = 1900 ; year <= 2200 ; year ++)
    {
        if ( esBisiesto (year))
        {
            printf ( " % ld , " , year);
        }
    }
    return  0 ;
}

 

94,340 points
11 6 5