[try Beta version]
Not logged in

 
Program to check whether a year is leap year or not

Nov 5, 2017 at 7:51pm
#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;
}
Nov 5, 2017 at 8:41pm
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 Nov 5, 2017 at 8:41pm
Nov 5, 2017 at 8:53pm
"If the left is true, the right will always be true"

false
Nov 5, 2017 at 9:13pm
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 !!
Nov 5, 2017 at 10:34pm
Nuts. That'll teach me to scan code too quickly.

What was the actual question?
Nov 7, 2017 at 9:36am
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;
}

Nov 7, 2017 at 3:04pm
@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 Nov 7, 2017 at 3:05pm
Nov 7, 2017 at 3:35pm
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.