# summing number of days between 2 months

• 11-03-2005
duff_johnny
summing number of days between 2 months
I'm stuck with a homework question - familiar story.

I must write a function that sums the total number of days from beggining of first argument (month 1) to the end of second argument (month2).

Have started off with a pair of if/elses to find number of days in month1 and month2 and summed them. Easy.

But can anyone help me find the sum of the days in the months inbetween? So I can add this to the sum of the two months in question.

Am i going about this totally the wrong way? It seems like the only way to do this is to program loads of if else's, surely theres a quicker way?

Any help most appreciated,
Johnny
• 11-03-2005
cbastard
• 11-03-2005
Ancient Dragon
start by creating an array of integers that contain the number of days in each month. Then just use normal array indicing method to add two elements gether. This will probably require a loop because there may be more than two mohths difference, such as from 1 Jan to 31 Dec is 12 months, not two, which means the program has to sum up all 12 array elements. And don't forget to account for leap years where February can be either 28 or 29 days.
• 11-03-2005
duff_johnny
think i've solved it by looping my if elses, i've posted below my if elses

Code:

```if (month ==2)          //if feb, 28days {numbDays = 28;   totalDays = totalDays + numdays; } else     if ( month == 1 || 3||... 11||12)          //if 31 days           {numDays = 31;             totalDays = totalDays + numDays;           }     else ()             {numDays = 30;                            //otherwise 30 days               totalDays = totalDays + numDays;             }```
previously i didn't have the totalDays bit. Now however, I'm looping all of this while (month1 <= month2) and keeping track of total in totalDays.

This should do it I think. Anyone got a better idea?
Cheers for the array suggestion, we're covering them soon but not yet, so i expect they're looking for an array free solution.

thanks,
Johnny
• 11-03-2005
Ancient Dragon
Code:

```int months[] = { 31, // January 28, // Feb 31, // Mar 30, // April 31, // May 30, // Jun 31, // July 31, // Aug 30, // Sep 31, // Oct 30, // Nov 31 // Dec } int main() {   int start_month = 1; // January   int end_month = 6; // June   int year = 2004; // needed for leap-year check   int m, total;   // there are some other leap-year conditions too, but this   // is sufficient for most purposes.   if( (year % 4) == 0)     months[1] = 29; // make February 29 days   // arrays are indexed from 0-11 so subtract one from each month   total = 0;    for(m = start_month-1; m < end_moth; m++)       total += months[m]; }```

Quote:

so i expect they're looking for an array free solution.
Sorry, I didn't notice that when I first posted this.
[/dit]
• 11-03-2005
duff_johnny
Thanks for the help. Problem now solved.

Johnny