# Justify a block of text

i am wondering what is the best way to justify a block of text. for example, right now i have a code that prints: 1 2 3 4 5 6 7 8 9 10 11 and so on, but i want it to print

1 2 3 4 5 6 7
10 11 12 13 14 15 16​

in other words, there is a new line at the end of the seventh number. this is the code:

Code:
int i = 0;
while (i < 31){
cout << setw(4) << i;
i++;
}

thanks

Mark44
Mentor
i am wondering what is the best way to justify a block of text. for example, right now i have a code that prints: 1 2 3 4 5 6 7 8 9 10 11 and so on, but i want it to print

1 2 3 4 5 6 7
10 11 12 13 14 15 16​
You skipped some numbers in the above.
in other words, there is a new line at the end of the seventh number. this is the code:

Code:
int i = 0;
while (i < 31){
cout << setw(4) << i;
i++;
}

thanks

You need some logic in your loop to print a newline character every seventh number. Also, the logic in your loop is off by one: it starts printing at 0 and ends at 30. The constant 31 makes me think that this is related to printing calendar months.

Code:
int i = 1;
while (i <= 31)
{
cout << setw(4) << i;
if (i % 7 == 0)
{
cout << endline;
}
i++;
}

This should give output like this:
1 2 3 4 5 6 7
8 9 10 11 12 13 14
...
22 23 24 25 26 27 28
29 30 31

ok, thanks for the help. but what if the numbers start at a different column? going with the idea of a calendar, if you started on say, wednesday it should look more like

1 2 3 4
5 6 7 8 9 10 11
and so on...

how do i modify the code to reflect something like that?

Mark44
Mentor
Your program logic needs to figure out what day of the week to start on. Most calendars that I'm familiar with start on Sunday, although one Italian calendar I had started on Monday.

If the first of the month falls on Sunday, then my preceding code works fine for months with 31 days. (Months with fewer days is another story, and the fix for that entails using a variable to control the while loop instead of hard-coding 31 in it.)

If the first of the month falls on some other day, your first row of numbers needs to start some number of spaces to the right, and needs to quit after the last day of the week. Using your example of the first falling on Wednesday, the program logic needs to start printing in the fourth column (the one for Wednesday), and needs to issue an endline after the 4th, 11th, 18th, and 25th. If i represents the day of the month, for these dates the expression i % 7 == 4.

Can you write the code that takes these ideas into account?

Code:
int day1;
switch (day1){
case 0: if (i % 7 == 0) cout << endl;
.
.
.
case 5: if (i % 7 == 2) cout << endl;
}

skipped a bunch b/c i think i get the idea

Mark44
Mentor
Don't forget that you need a break statement in each case.