How to get the number of days in a given month of a given year with C++

1 Answer

0 votes
#include <iostream>
 
bool isLeapYear(int year) {
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
 
int daysInMonth(int year, int month) {
    int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

    if (month == 2 && isLeapYear(year)) {
        return 29;
    }
     
    return days[month - 1];
}
 
int main() {
    int year = 2024;
    int month = 2;
     
    std::cout << "Days in month: " << daysInMonth(year, month) << std::endl;
    std::cout << "Days in month: " << daysInMonth(2025, 1) << std::endl;
    std::cout << "Days in month: " << daysInMonth(2025, 2) << std::endl;
    std::cout << "Days in month: " << daysInMonth(2025, 4) << std::endl;
    
}

  
  
/*
run:
  
Days in month: 29
Days in month: 31
Days in month: 28
Days in month: 30
  
*/

 



answered Feb 19, 2025 by avibootz
edited Feb 19, 2025 by avibootz
...