Alex Alex - 1 month ago 11
C Question

I'm trying to print a calender, but I couldn't get my result aligned

This is what I've done so far.

#include<stdio.h>

int main()
{
int days, start, i, j;

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

printf("Enter starting day of the week (1=Sun, 2=Mon, ......, 7=Sat): ");
scanf("%d", &start);

printf("Sun Mon Tue Wed Thu Fri Sat\n");

for(i=0; i<(start-1); i++)
printf(" ");

for(j=1; j<=days; j++){
printf("%3d", j);

if((j+i)%7==0)
printf("\n");}

printf("\n\n");

return 0;

}


This is my result:
result

Can anybody tell me where's wrong? I'm new to programming, so I'll appreciate if you can write the answers in a simpler way. Thank you so much!

Answer

Instead of

    printf("Sun Mon Tue Wed Thu Fri Sat\n");

use

    printf("\n Sun Mon Tue Wed Thu Fri Sat\n");    // New line and an extra space

then instead of

    printf("    ");

use

    printf("     ");                               // 5 spaces instead of 4

and instead of

    printf("%3d", j);

use

    printf("%4d", j);                              // 4 positions (1 for an extra space)