Finding the dates of a specific weekday within a month

Viewed 39

solved question

I'm trying to find the dates within a specific month in 2022 on which a specific weekday will occur i.e. August and Saturday so 6,13,20,27th.

I have a function I can use to find what the first weekday within a month is, again using August 2022 as an example this would be a Monday.

int valid_dname(char *md, char *m){
   struct tm   tm;
   int year = 2022;
    memset(&tm, 0, sizeof(tm));

    tm.tm_mday  = atoi(md);
    tm.tm_mon   = atoi(m);
    tm.tm_year  = year-1900;
    mktime(&tm);

    return tm.tm_wday;
}

Having the weekdays being equivalent to numbers (Sun-0...Sat-6), I want to create an array into which I can put the first day of the month and then fill in the date in which the rest of the weekdays fall within the first week. Like this:

0,1,2,3,4,5,6 <-- day of the week in number form [7,1,2,3,4,5,6]

From here I'd just be doing basic calculations however, I'm currently stuck on how to make the incrementer loop around the array once I get to the Saturday(6), to be able to put a 7 within the Sunday slot.

Hope this makes sense. :)

1 Answers

I'm not certain this is exactly what you are looking for, but it may be going in the direction you want...

void fillArr( int d1, int arr[] ) {
    for( int i = 0; i < 7; i++, d1++ )
        arr[ d1 % 7 ] = i+1;
}

void showArr( int arr[] ) {
    for( int i = 0; i < 7; i++ )
        printf( "[%d] %d, ", i, arr[ i ] );
    putchar( '\n' );
}

int main() {
    int arr[ 7 ];

    fillArr( 1, arr ); // 1 = Monday for Aug
    showArr( arr );

    fillArr( 4, arr ); // 4 = Thursday for Sep
    showArr( arr );

    return 0;
}

Output

[0] 7, [1] 1, [2] 2, [3] 3, [4] 4, [5] 5, [6] 6, // 1=Mon 01 Aug 22
[0] 4, [1] 5, [2] 6, [3] 7, [4] 1, [5] 2, [6] 3, // 1=Thu 01 Sep 22
Related