0

I corrected my function to read

```
int calcDays (int)
{
int month = 0;
int numberOfDays;
int year = 0;
if (month == 4 || month == 6 || month == 9 || month == 11)
numberOfDays = 30;
else if (month == 02)
{
bool isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
if (isLeapYear == 0)
numberOfDays = 29;
else
numberOfDays = 28;
}
else
numberOfDays = 31;
return numberOfDays;
}
```

however I still get the error that numberOfDays is not initialized....not sure where to "initialize" it and have it return the correct value.....

0

Read this.

Now, take a look at the first line of your function...

`int calcDays (int)`

Anything missing?

0

I know the OP did this *YEARS* ago, but here's how the function should look for anyone who wants to do this:

```
int calcDays(int month, int year)
{
int Days;
if (month == 4 || month == 6 || month == 9 || month == 11) Days = 30;
else if (month == 2) {
bool isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
if (isLeapYear) Days = 29;
else Days = 28;
}
else Days = 31;
return Days;
}
```

0

I know the OP did this YEARS ago, but here's how the function should look for anyone who wants to do this:

Since we're talking about other people who want to do this, a table lookup is the recommended solution:

```
#include <exception>
#include <iostream>
#include <stdexcept>
inline int is_leap(int year)
{
return year > 0 && !(year % 4) && (year % 100 || !(year % 400));
};
int calcDays(int month, int year)
{
static const int monthdays[2][13] = {
{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
{ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
};
if (month < 1 || month > 12) {
throw std::invalid_argument("Invalid month");
}
return monthdays[is_leap(year)][month - 1];
}
int main()
{
std::cout << "\t2000\t2001\n";
for (int i = -1; i < 15; i++) {
try {
std::cout << i << ":\t";
std::cout << calcDays(i, 2000) << '\t' << calcDays(i, 2001) << '\n';
} catch (const std::exception& ex) {
std::cout << ex.what() << '\n';
}
}
}
```

You

This article has been dead for over six months: Start a new discussion instead