Paul Allen Paul Allen - 1 year ago 38 Question

Print a multiplication table using VB.Net

When I try to print a multiplication table using the following code,

Dim se As String
Label1.Text = Space(35) & "九九乘法表" & vbCrLf
Label1.Text &= Space(35) & "-----------" & vbCrLf
For i = 1 To 9
Label1.Text &= Space(8 * (i - 1) + i)
For j = i To 9
se = i & "×" & j & "=" & i * j
Label1.Text &= se & Space(8 - Len(se))
Next j
Label1.Text &= vbCrLf
Next i

it gives me a well-aligned table as I want as the picture below

enter image description here

If I change the
Label1.Text &= Space(8 * (i - 1) + i)
in line 5

Label1.Text &= Space(8 * (i - 1) )
, the table turns out to be like this:

enter image description here

I guess my question will be: Why I have to add "i" spaces more?

Thanks Edper for his answer.

But I'm just confused why such an additional incrementing space is necessary?

Let's say I'm using
Label1.Text &= Space(8 * (i - 1) )
, then there will be no space in the 1st loop, 8 spaces in the 2nd loop, 16 spaces in the 3rd loop... , why won't that make all the equations align?

More specifically, after the equation 1x1=1, there are 3 spaces, so right before 1x2=2, there are 8 characters, then if I have 8 spaces in the 2nd loop, 2x2=4 should have aligned with 1x2=2, but it didn't. That's what I'm wondering about.


What font did you use for the Label1 control? From the screen capture, I can see that you are not using a fixed-width font.

If you change the font to fixed-width font family (eg: Courier New) you will get a perfectly aligned table with the code Label1.Text &= Space(8 * (i - 1)), while with ...) + i) code will give you a table with unaligned columns.

The reason for this is, fixed-width fonts have the same width for every characters in the set, at any font size. This include the space (Chr(32)) too. While non fixed-width fonts, each character have different width. Eg: the letter W is wider than i. And spaces will have different width too.

For example:

Fixed-width font:


Non fixed-width font:


You can see above, in both 'table' above, I put 7 dots to push the second row to align to the second column of the first row. And in the table using non fixed-width font, the 2x2=4 appears to the left to where it should be.

That means, since the space is narrower, you need to append more spaces to make it aligned like below:


In the sample table above, I have to put in 13 dots to make it appear aligned (or close enough). Since this page is using some other font to display this table.

In your case, you are just lucky enough that the font you are using can be aligned perfectly by simply adding i.