 # Leap Year Exercise

Hello everyone and thanks for helping each other.
I decided I’ll try to learn the basics of C++ now I’m stuck on the leap year exercise…
I wanted on purpose to write it in a different way then there’s in the hint, so I wanted to add booleans, which I’ll use in the final if statement to decide if the year is a leap one.
But… my code detects years which are common as leap (not the other way though).
Would anyone be so kind and look at my code, to tell me what’s wrong?

``````#include <iostream>

int main() {
int y;
bool divfour;
bool divhunnotF;
bool divFourH;
std::cout << "Enter year ";
std::cin >> y;

if (y%4 == 0) // if I can divide by four set divfour to true
{divfour = true;}

else if (y%100==0 and y%400!=0) // if can evenly divide by 100, but not by 400 assign true
{divhunnotF = true;}

else if (y%400==0) // if can divide by 400 assign true
{divFourH = true;}

if (divfour and !divhunnotF and divFourH) // if divfour is true, divhunnotF isn't and divfourH is, then it's a leap year,right?
{
std::cout << "Leap year\n";
}
else
{
std::cout << "not leap year\n";
}
}
``````

Thanks anyone who bothers to check in advance 1 Like

Hello, @vojtchuxa5203701085, and welcome to the forums.

Consider the logic of your program. Place your finger on the first line of code, and execute each line as if you were the computer. Try a known leap year like 2020. Are you able to check each condition, or does control pass up one or more? Also consider whether you need to check `y % 400` twice? (Two booleans would suffice.)

Hint
``````//this logic is flawed:
else if (y%100==0 and y%400!=0) // if can evenly divide by 100, but not by 400 assign true
{divhunnotF = true;}
//if the year is evenly divisible by both 100 and 400 it is a leap year
//more specifically if it is evenly divisible by 100 it is only a leap year if it is also evenly divisible by 400
``````

Consider this method of assigning boolean values:

``````bool myBool = 10 % 2 == 0; //assigns true (1)
bool myOtherBool = 10 % 3 == 0; //assigns false (0)
``````

No real need for `if...else if`.

1 Like

Thank you!!!
I finally was able to put my finger on what’s wrong…
I don’t know you could add the math clause to assigning boolean values, I guess I’m not that far into the course yet, but I was able to construct my if clause correctly now!

``````
#include <iostream>

int main() {

int y;

std::cout << "Enter year ";

std::cin >> y;

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

// if divide by 4 is 0, divide by 100 is not 0 or divisble by 400 is 0

{

std::cout << "Leap year \n";

}

else

std::cout << "So not leap year \n";

}
``````

This is what I figured thanks for assistance!

1 Like