Alex
Alex

Reputation: 25

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!

Upvotes: 2

Views: 69

Answers (3)

user3629249
user3629249

Reputation: 16540

each day number needs to be printed in the same width (4 columns) so the print statement should look something like

printf("%4.4d", j);

which will have all the numbers 1 space to the right.

This could be corrected in two ways

1) insert a space at the beginning of the literal that prints out the column headers (my preference)

or

2) check to see if it is the first entry in a line and use a print statement similar to, only for that first entry:

printf("%3,3d", j);

Upvotes: 0

MarianD
MarianD

Reputation: 14181

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)

Upvotes: 1

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

Nearly correct. A correct version is:

int main(void)
{
    int days=30, start=3, i, j;

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

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

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

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

You don't need to increment i in the loop and you had to allign the output.

Output:

Sun Mon Tue Wed Thu Fri Sat
          1   2   3   4   5 
  6   7   8   9  10  11  12 
 13  14  15  16  17  18  19 
 20  21  22  23  24  25  26 
 27  28  29  30 

Upvotes: 0

Related Questions