Wednesday, 15 June 2011

c - Incrementing nested arrays - with date information -



c - Incrementing nested arrays - with date information -

i have 3 integer arrays. size 365.

double month[size], day[size]; int countmonths[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

in month array want populate int value of month - first 31 fields have 1, next 28 fields have 2, etc. amount of days in month.

month[0-31] have value 1 (corresponding month 1) month[32-60] value 2 (corresponding month 2)

my loop not working. outer loop cycle through 365 items in array. wanted inner loop cycle amount of - corresponding values in countmonths[1] etc. ;

for (int = 0; < size; i++) for(int j = 1; j < countmonths[j]; j++) month[i] = i+1;

the sec query using same countmonths inner loop have update instead of putting values 1 (corresponding month 1). set 1, 2, 3 etc. until gets 31 , start @ 1 again.

for (int = 0; < size; i++) for(int j = 1; j < countmonths[j]; j++) day[i] = j;

neither query doing want ... please advise. using below logic seem update , cycle through first of each month.

int = 0; int currentmonth = 0; int currentday = 1; while(i < size && < countmonths[currentmonth]) { month[i] = currentmonth+1; day[i] = currentday; i++; currentday++; if(currentday > countmonths[currentmonth]); { currentmonth++; currentday = 1; } }

you using 2 indexes 2 loops, when more useful utilize 3 indexes in 1 loop:

currentday = currentmonth = 1 while(destinationindex , currentmonth valid indexes) assign current day , month destination arrays increment destinationindex , currentday if(currentday greater possible currentmonth) increment currentmonth set currentday 1

c arrays for-loop nested nested-loops

No comments:

Post a Comment