pOrinG
pOrinG

Reputation: 935

Loop over months in C

Currently I am having 2 variables storing year month in it.

Example:

var1 : 201711

var2 : 201801

Firstly I want to find if both the months in the variable are consecutive year months or not. If not then I would like create a loop so that I can get the months between var1&2.

if( MonthsDifference(var2,var1) = 1 )
{
    ....
}
else
{
     for ( a = 1 ; a <= MonthsDifference(var2 - var1) ; a++)
     {
           printf("Next month is:[%d]",addmonths(var1,1));
     }
}

I am having trouble imagining a logic to get the Months difference & also to add months effectively. Value type & data(year-month) stored in var1 & 2 is flexible and can be in any way preferable.

Thanks in advance.

Upvotes: 2

Views: 114

Answers (2)

einpoklum
einpoklum

Reputation: 132036

It seems the encoding scheme for years and months in your two variables are:

combined_value = year * 100 + month

So the lower two decimal digits are the month, the upper digits (typically 4) are the year. Well, we know how to extract decimal digits in C:

lower_decimal_digit = num % 10
lower_2_decimal_digits = num % 100

and so on (we can also do this with a variable number of digits but that's not necessary here). Similarly, we can keep only the higher digits:

all_but_lower_decimal_digit = num / 10
all_but_lower_2_decimal_digits = num / 100

so in your case, the two commands:

int year = combined / 100;
int month = combined % 100;

do the trick. I'm sure you can proceed from there.

Upvotes: 1

The conventional to iterate over a list is

for (var = first_item; end_not_reached(var); var = next_after(var))

Your encoding has the correct order of dates, i.e. var1 <= var2 when var1 is earlier than var2. Therefore, to check whether you've reached the end of the list, all you need to do is compare the iterator with the end date.

The next month after a given date is given by the following function:

int next_month(int date) {
    return date % 100 == 12 ? date + 89 : date + 1;
}

Thus:

if (next_month(var1) == var2)
    ... // the months are consecutive with var1 just before var2

for (var = var1; var <= var2; var = next_month(var)) {
    …
}

Upvotes: 1

Related Questions