Search code examples
c++loopsif-statementleap-year

When I input 1900 for the year and 2 for the month I get 29 when it should be 28


Write a program month.cpp that asks the user to input the year and the month (1-12) and prints the number of days in that month (taking into account leap years). You may not use switch case or arrays even if you know these language constructs.

I understand using namespace std is a bad practice. However, my professor wants us to learn like this as of now.

I think I am making a mistake with my loop for February, but I don't know what it might be.

#include <iostream>

using namespace std;

int main(){
    int year = 0;
    int month = 0;
    cout << "Enter year: ";
    cin >> year;
    cout << endl;
    cout << "Enter Month: ";
    cin >> month;
    cout << endl;


    if (month == 1){
        cout << "31 days" << endl;
    }
    if (month == 2){
        if (year % 4){
            cout << "29 days" << endl;
        }
        else{
            cout << "28 days" << endl;

        }
    }    

    if (month == 3){
        cout << "31 days" << endl;
        }
    if (month == 4){
        cout << "30 days" << endl;

    }
    if (month == 5){
        cout << "31 days" << endl;
    }
    if (month == 6) {
        cout << "30 days" << endl;
    }
    if (month == 7){
        cout << "31 days" << endl;
        }
    if (month == 8){
        cout << "31 days" << endl;

    }
    if (month == 9){
        cout << "30 days" << endl;
    }
    if (month == 10) {
        cout << "31 days" << endl;
    }
    if (month == 11){
        cout << "30 days" << endl;
    }
    if (month == 12) {
        cout << "31 days" << endl;
    }

    return 0;
}

Solution

  • The problem occurs in the if(year%4) statement. I'm guessing that you're meaning to say "when the year is divisible by 4, output 29 days".

    However, your if-statement does not actually do this.

    This if-statement first evaluates (year%4) then outputs 29 days if it ends up being true. In C++, an expression is true when it is not equal to 0.

    Thus, year%4 evaluates to true when year%4 isn't equal to zero; it is the exact opposite of what you actually meant to do.

    To fix this, simply replace your if-statement with if(year%4 == 0).

    EDIT: The leap-year criterion is actually quite a bit more complicated; for a year to be a leap year, it must either be divisible by 400 or divisible by 4 and not 100.

    In the end, the if-statement should look like this:

    if(month == 2){
        if((year % 400 == 0) || (year%4 == 0 && year%100 != 0)){
            cout << "29 days" << endl;
        }
        else{
            cout << "28 days" << endl;
        }
    }