-4

I know my code is close but it doesn't quite work.

It supposed to take in the day of the week the calendar starts on and the number of days in the month.

Can I please get help correcting?

int main(void)
{
    int start_day, days_in_month, i, day_of_week;

    printf("Enter start day: ");
    scanf("%d", &start_day);

    printf("Enter days in month: ");
    scanf("%d", &days_in_month);

    for (i = 1 ; i < start_day; i++) {
        printf("   ");
    }

    for (i = 1; i <= days_in_month; i++) {
        printf("%2d ", i);
        if ((i + start_day - 1) % 7 == 0) {
            printf("\n");
        }
    }
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
Ben
  • 1
  • 7
    Correcting what? Please be more specific than "doesn't quite work". Specifically, please tell us the test input, the expected output and the actual output. – kaylum Jan 30 '16 at 05:30
  • 1
    Works for me. Not sure what you think is wrong with it. – user3386109 Jan 30 '16 at 06:06

1 Answers1

1

I can see a few small issues:

  • You should add #include <stdio.h>
  • You should not define day_of_week since you do not use it.
  • You might want to avoid printing a space at the end of each line.
  • You should output an extra line feed after the calendar if the last line is incomplete.
  • You should test the return value of scanf and abort if no number was input, to avoid undefined behavior.

Here is a corrected version:

#include <stdio.h>

int main(void) {
    int start_day, days_in_month, i;

    printf("Enter start day: ");
    if (scanf("%d", &start_day) != 1)
        return 1;

    printf("Enter days in month: ");
    if (scanf("%d", &days_in_month) != 1)
        return 1;

    for (i = 1; i < start_day; i++) {
        printf("   ");
    }

    for (i = 1; i <= days_in_month; i++) {
        printf("%2d", i);
        if ((i + start_day - 1) % 7 == 0) {
            printf("\n");
        } else {
            printf(" ");
        }
    }
    if ((days_in_month + start_day - 1) % 7 != 0) {
        printf("\n");
    }
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189