The question and the code is given for the question below I

// The question and the code is given for the question below. I just need an explanation for the line that I typed in bold in the code below. Thanks.

Here are three definitions:

a. Def: A year y is a century year if y is divisible by 100.

Example: y=300 is a century year, but y=150 is not.

b. Def: A year y is a non-century year if y is not a century year.

Example: y=150 is a non century year. Y=4 is a non-century year.

c. Def: a year y is a leap year if it is a non-century year that is divisible by 4, or a century year that is divisible

by 400. Nothing else is a leap year.

Example: y=4 is a leap year, y=100 is not a leap year, y=400 is a leap year.

Question: a Write a function

bool leapyear(int y)

that when passed a year y will return true if y is a leap year and false if not.

bool leapyear(int y) //Function definition   
{
if(y%4==0 || y%100!=0 && y%400==0) // Please explain this!
{
return true;
}
else
{
return false;
}
}

Solution

There are many operations here. The order of precedence is that first modulus wihh be executed and the equal to condition will be executed then && and finally ||. So if we put brackets here just to make it clear.

if( ( (y%4)==0 ) || ( ( (y%100)!=0) && ( (y%400)==0 ) ) )

So the condition check if (y is divisble by 4) or (y is not divisible by 100 and is divisible by 400). This condition does not actually identify loop years correctly, because of the first time when we check if y is divisible by 4, even years like 1700 will be divisible 4 but they are not actually leap years. If you substitue y in the equation. y%4==0 is true, although the next condition is false. Because of the or the total equation will be true.

// The question and the code is given for the question below. I just need an explanation for the line that I typed in bold in the code below. Thanks. Here are t

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site