Program to check whether a year is leap year or not

#include<iostream>
using namespace std;
int main()
{
int year;
cout << "Enter an Year=";
cin >> year;
if (year % 4 == 0 || year % 400 == 0)
cout << "This is a Leap year" << endl;
else if (year % 100 != 0)
cout << "This is Not Leap year" << endl;
return 0;
}
if (year % 4 == 0 || year % 400 == 0)

This looks suspicious.

If the left is true, the right will always be true; if the left is false, the right will be false.

So why does the right exist?
Last edited on
"If the left is true, the right will always be true"

false
Guys, srsly ... try it with 2004 :

2004 % 4 = 0
2004 % 400 = 4

So no if the left is true the right will not always be true !!
Nuts. That'll teach me to scan code too quickly.

What was the actual question?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include<iostream>

int main()
{
    std::cout << "Enter an year: ";
    int year = 0;
    std::cin >> year;
    // An year is leap if:
    // - BOTH can be evenly divide by 4
    // - AND if can be evenly divided by 100, can be divided by 400 TOO
    if (year % 4 == 0) {
        if(year % 100 != 0) { // it can't be divided by 100, but it can by 4: it's leap
            std::cout << "This is a leap year\n";
        } else if(year % 400 == 0) {
            std::cout << "This is a leap year\n";
        } else {
            std::cout << "This is not a leap year\n";
        }
    } else {
        std::cout << "This is not a leap year\n";
    }
    
    // A more 'compressed' logic is:
    // An year is leap if:
    // - EITHER can be evenly divide by 4 AND can NOT be divided by 100
    // - OR it can be divided by 400
    if( (0 == year % 4 && 0 != year % 100) || (0 == year % 400) ) {
        std::cout << "This is a leap year\n";
    } else {
        std::cout << "This is not a leap year\n";
    }
    return 0;
}

@Enoizat

Your code will output "This is a leap year" twice if the year is 400 or some other values. So this is a flawed program.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace std;

bool isLeap( int year ) { return !( year % 4 ) && ( year % 100 || !( year % 400 ) ); }

int main()
{
   int year;
   cout << "Enter year: ";   cin >> year;
   cout << year << ( isLeap( year ) ? " is " : " is not " ) << "a leap year";
}
Topic archived. No new replies allowed.