Search code examples
turbo-c++turbo-c

A program that inputs a year and displays “Leap year "if it is leap year or "Not leap year" if it is not leap year without using the modulus symbol


So far I've come up with this however it doesn't seem to output results consistently.

if (year/4*4==year)
{
cout<<"It is a leap year!";
}
else
{
cout<<"It is not a leap year!";
}

How can i solve this?


Solution

  • If you want to check if some years entered by the user are leap years or not, you just have to write a loop.

    In my code I also added an helper function (Turbo C++ has bool type, right? It's part of the standard...) with the exact formula (you can find that online). Note that the loop ends when the user inputs something that is not an integer (or EOF).

    #include <iostream>
    
    bool is_leap( int y )
    {
        return  y % 400 == 0  ||  ( y % 100 != 0  &&  y % 4 == 0 );
    }
    
    int main()
    {
        int year;
    
        while ( std::cin >> year )
        {
            if ( is_leap(year) )
            {
                std::cout << year << " is a leap year!\n";
            }
            else
            {
                std::cout << year << " is not a leap year.\n";
            }
        }
    
        return 0;
    }
    

    For example, you can try:

    1857 is not a leap year.
    1900 is not a leap year.
    1980 is a leap year!
    1991 is not a leap year.
    2000 is a leap year!
    2016 is a leap year!