### Leap Year Program Help

Hello, I've been having some trouble for my class assignment. I'm supposed to input a year and then it will output if the year is a leap-year or not.

 A year with 366 days is called a leap year. A year is a leap year if it is divisible by four (for example, 1980), except that it is not a leap year if it is divisible by 100 (for example, 1900); however, it is a leap year if it is divisible by 400 (for example, 2000). There were no exceptions before the introduction of the Gregorian calendar on October 15, 1582 (1500 was a leap year). Write a program that asks the user for a year and computes whether that year is a leap year.

Here is my code so far.

 123456789101112131415161718192021222324252627 #include using namespace std; int main() { int number; cout << "Enter a year. " << endl; cin >> number; if (number % 4 == 0) { if (number % 100 != 0) { if (number % 400 == 0) { cout << "The year is a leap year." << endl; } } } else { cout << "The year isn't a leap year." << endl; } return 0; }

I'm just not sure where I went wrong here.. I'm not asking anyone to do my homework here, just some help in the right direction would be appreciated.

Thanks!
Last edited on
These conditions

if (number % 100 != 0)
{
if (number % 400 == 0)
{
contradict each other. That is if number % 100 != 0 then it is not a value that is divisible by 400. Also you have not enough ellse statements that to print messages that a year is not leap.
You don't want to nest the last if you have there, it should be part of an if...else if statement, like this:

 123456789 if(number % 4 == 0) { if (number % 400 == 0) // leap year else if (number % 100 == 0) // not a leap year else //leap year }

There's probably a better way to do this but this should put you on the right track.
@freddy92
You don't want to nest the last if you have there, it should be part of an if...else if statement, like this:
 123456789 if(number % 4 == 0) { if (number % 400 == 0) // leap year else if (number % 100 == 0) // not a leap year else //leap year }

I would rewrite your code snip the following way

 12345678 if ( number % 400 == 0 ) // leap year else if ( number % 100 == 0 ) // not a leap year else if ( number % 4 == 0 ) //leap year else // not a leap year

But in any case it is more simply to write

 12345678 if ( number % 4 == 0 && ( number % 100 != 0 || number % 400 == 0 ) ) { cout << "The year is a leap year." << endl; } else { cout << "The year isn't a leap year." << endl; }

Or even the following way

 123456 auto IsLeap = []( int year ) { return ( year % 4 == 0 && ( year % 100 != 0 || year % 400 == 0 ) ); }; cout << "The year is " << ( IsLeap( number ) ? "" : "not " ) << "a leap year." << endl;
Last edited on
Thanks guys so much for the help. I'm positive I can rewrite the code the right way now!
Topic archived. No new replies allowed.