c++for-loopswitch-statement

Return number of days in a given month of a given year


I wrote a program that, given the month number and the year, returns the number of days in that month:

#include <iostream.h>
#include <conio.h>
void main() {
  clrscr();
  int month, year, i;
  cout << "give the year \n";
  cin >> year;
  cout << "give the month\n";
  cin >> month;
  for (i = 1; i <= 12; i++) {
    i = month;
    switch (month) {
      case 1:
        cout << "number of day in month is 31\n";
        break;
      case 2:
        if (year % 4 == 0) {
          cout << "the number of days is 29 \n";
        } else {
          cout << "the number of days is 28 \n";
        }
        break;
      case 3, 5, 7, 8, 10, 12:
        cout << "the number of days is 31 \n";
        break;
      default:
        cout << "the number of days is 30 \n";
        return;
    }
  }
  return;
}

When I give the month number 3, it returns the number of days is 31, so it works fine. But when I give 1 or 2, the output is

number of day in month is 31
number of day in month is 31
number of day in month is 31
.
.
.
.

How can I make it return only number of day in month is 31 or number of day in month is 28 if the case is 2?


Solution

  • Don't repeat the calculation/ don't use the loop. Use the switch case syntax properly.

    And your leap year calculation is wrong. It should be like this:

    if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)){
        cout << "the number of days is 29 \n";
    }
    else {
        cout << "the number of days is 28 \n";
    }
    

    A year is leap year if it is divisible by 4 but not divisible by 100 or it is divisible by 400