1
$\begingroup$

I'm creating some multi-column tables with multi-line headings. The following is an example

enter image description here

I created the above table using the Table statement as follows

powersTable[n_]:=TableForm[Prepend[PrependTo[Table[{i,i^2,i^3},{i,1,n}],{--,---,-----}],{n ,n^2,n^3}]]

This works nicely but is a little awkward with the nested Prepends, so I'd like to do it with a For loop and Print along the following lines

    powersTable2[n_]:=(Print[n     n^2      n^3
----  ------   ------];For[i=1,i<=10,i++,Print[i,     ,i^2,         ,i^3]])

This produces the correct output, as seen below

enter image description here

but with 2 formatting problems: (1) the output is double-spaced and (2) the column data is not alined as it is in the Table version.

Is there any way to reproduce the Table version output using Print and For?

$\endgroup$

2 Answers 2

5
$\begingroup$

I don't think you need to resort to Print or For. I think TableForm can do what you want by applying one of its options.

powers[n_Integer?Positive] := Table[{i, i^2, i^3}, {i, n}]
TableForm[powers[5], TableHeadings -> {None, {n, n^2, n^3}}]

powers

$\endgroup$
2
$\begingroup$

You could also try using the Grid function. This provides much more control for formatting tabular/grid data and allows properties such as font characteristics, background colours, divider characteristics, etc. to be specified at row, column and cell level. See the documentation for more details and examples. Hope this helps, Ian

$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.