Multiplication tables

From Rosetta Code
Jump to: navigation, search
Task
Multiplication tables
You are encouraged to solve this task according to the task description, using any language you may know.

Produce a formatted 12×12 multiplication table of the kind memorised by rote when in primary school.

Only print the top half triangle of products.

Contents

[edit] ActionScript

 
package {
 
import flash.display.Sprite;
import flash.events.Event;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
 
[SWF (width = 550, height = 550)]
public class MultiplicationTable extends Sprite {
 
public function MultiplicationTable() {
if ( stage ) _init();
else addEventListener(Event.ADDED_TO_STAGE, _init);
}
 
private function _init(e:Event = null):void {
 
removeEventListener(Event.ADDED_TO_STAGE, _init);
 
var format:TextFormat = new TextFormat();
format.size = 15;
var blockSize:uint = 40;
var max:uint = 12;
 
var i:uint, j:uint;
var tf:TextField;
 
for ( i = 1; i <= max; i++ ) {
tf = new TextField();
tf.defaultTextFormat = format;
tf.x = blockSize * i;
tf.y = 0;
tf.width = tf.height = blockSize;
tf.autoSize = TextFieldAutoSize.CENTER;
tf.text = String(i);
addChild(tf);
 
tf = new TextField();
tf.defaultTextFormat = format;
tf.x = 0;
tf.y = blockSize * i;
tf.width = tf.height = blockSize;
tf.autoSize = TextFieldAutoSize.CENTER;
tf.text = String(i);
addChild(tf);
}
 
var yOffset:Number = tf.textHeight / 2;
y += yOffset;
 
graphics.lineStyle(1, 0x000000);
graphics.moveTo(blockSize, -yOffset);
graphics.lineTo(blockSize, (blockSize * (max + 1)) - yOffset);
graphics.moveTo(0, blockSize - yOffset);
graphics.lineTo(blockSize * (max + 1), blockSize - yOffset);
 
 
for ( i = 1; i <= max; i++ ) {
for ( j = 1; j <= max; j++ ) {
if ( j > i )
continue;
 
tf = new TextField();
tf.defaultTextFormat = format;
tf.x = blockSize * i;
tf.y = blockSize * j;
tf.width = tf.height = blockSize;
tf.autoSize = TextFieldAutoSize.CENTER;
tf.text = String(i * j);
addChild(tf);
}
}
 
}
 
}
 
}
 

[edit] Ada

 
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
procedure Multiplication_Table is
package IO is new Integer_IO (Integer);
use IO;
begin
Put (" | ");
for Row in 1..12 loop
Put (Row, Width => 4);
end loop;
New_Line;
Put_Line ("--+-" & 12 * 4 * '-');
for Row in 1..12 loop
Put (Row, Width => 2);
Put ("| ");
for Column in 1..12 loop
if Column < Row then
Put (" ");
else
Put (Row * Column, Width => 4);
end if;
end loop;
New_Line;
end loop;
end Multiplication_Table;
 
  |    1   2   3   4   5   6   7   8   9  10  11  12
--+-------------------------------------------------
 1|    1   2   3   4   5   6   7   8   9  10  11  12
 2|        4   6   8  10  12  14  16  18  20  22  24
 3|            9  12  15  18  21  24  27  30  33  36
 4|               16  20  24  28  32  36  40  44  48
 5|                   25  30  35  40  45  50  55  60
 6|                       36  42  48  54  60  66  72
 7|                           49  56  63  70  77  84
 8|                               64  72  80  88  96
 9|                                   81  90  99 108
10|                                      100 110 120
11|                                          121 132
12|                                              144

[edit] ALGOL 68

Works with: ALGOL 68 version Standard - no extensions to language used
Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny
main:(
INT max = 12;
INT width = ENTIER(log(max)*2)+1;
STRING empty = " "*width, sep="|", hr = "+" + (max+1)*(width*"-"+"+");
FORMAT ifmt = $g(-width)"|"$; # remove leading zeros #
 
printf(($gl$, hr));
print(sep + IF width<2 THEN "x" ELSE " "*(width-2)+"x " FI + sep);
FOR col TO max DO printf((ifmt, col)) OD;
printf(($lgl$, hr));
 
FOR row TO max DO
[row:max]INT product;
FOR col FROM row TO max DO product[col]:=row*col OD;
STRING prefix=(empty+sep)*(row-1);
printf(($g$, sep, ifmt, row, $g$, prefix, ifmt, product, $l$))
OD;
printf(($gl$, hr))
)

Output:

+---+---+---+---+---+---+---+---+---+---+---+---+---+
| x |  1|  2|  3|  4|  5|  6|  7|  8|  9| 10| 11| 12|
+---+---+---+---+---+---+---+---+---+---+---+---+---+
|  1|  1|  2|  3|  4|  5|  6|  7|  8|  9| 10| 11| 12|
|  2|   |  4|  6|  8| 10| 12| 14| 16| 18| 20| 22| 24|
|  3|   |   |  9| 12| 15| 18| 21| 24| 27| 30| 33| 36|
|  4|   |   |   | 16| 20| 24| 28| 32| 36| 40| 44| 48|
|  5|   |   |   |   | 25| 30| 35| 40| 45| 50| 55| 60|
|  6|   |   |   |   |   | 36| 42| 48| 54| 60| 66| 72|
|  7|   |   |   |   |   |   | 49| 56| 63| 70| 77| 84|
|  8|   |   |   |   |   |   |   | 64| 72| 80| 88| 96|
|  9|   |   |   |   |   |   |   |   | 81| 90| 99|108|
| 10|   |   |   |   |   |   |   |   |   |100|110|120|
| 11|   |   |   |   |   |   |   |   |   |   |121|132|
| 12|   |   |   |   |   |   |   |   |   |   |   |144|
+---+---+---+---+---+---+---+---+---+---+---+---+---+

[edit] AppleScript

set n to 12 -- Size of table.
repeat with x from 0 to n
if x = 0 then set {table, x} to {{return}, -1}
repeat with y from 0 to n
if y's contents = 0 then
if x > 0 then set row to {f(x)}
if x = -1 then set {row, x} to {{f("x")}, 1}
else
if y ≥ x then set end of row to f(x * y)
if y < x then set end of row to f("")
end if
end repeat
set end of table to row & return
end repeat
return table as string
 
-- Handler/Function for formatting fixed width integer string.
on f(x)
set text item delimiters to ""
return (characters -4 thru -1 of (" " & x)) as string
end f
Output:
"
   x   1   2   3   4   5   6   7   8   9  10  11  12
   1   1   2   3   4   5   6   7   8   9  10  11  12
   2       4   6   8  10  12  14  16  18  20  22  24
   3           9  12  15  18  21  24  27  30  33  36
   4              16  20  24  28  32  36  40  44  48
   5                  25  30  35  40  45  50  55  60
   6                      36  42  48  54  60  66  72
   7                          49  56  63  70  77  84
   8                              64  72  80  88  96
   9                                  81  90  99 108
  10                                     100 110 120
  11                                         121 132
  12                                             144
"

[edit] AutoHotkey

Gui, -MinimizeBox
Gui, Margin, 0, 0
Gui, Font, s9, Fixedsys
Gui, Add, Edit, h0 w0
Gui, Add, Edit, w432 r14 -VScroll
Gosub, Table
Gui, Show,, Multiplication Table
Return
 
GuiClose:
GuiEscape:
ExitApp
Return
 
Table:
; top row
Table := " x |"
Loop, 12
Table .= SubStr(" " A_Index, -3)
Table .= "`n"
 
; underlines
Table .= "----+"
Loop, 48
Table .= "-"
Table .= "`n"
 
; table
Loop, 12 { ; rows
Table .= SubStr(" " Row := A_Index, -2) " |"
Loop, 12 ; columns
Table .= SubStr(" " (A_Index >= Row ? A_Index * Row : ""), -3)
Table .= "`n"
}
GuiControl,, Edit2, %Table%
Return

Message box shows:

  x |   1   2   3   4   5   6   7   8   9  10  11  12
----+------------------------------------------------
  1 |   1   2   3   4   5   6   7   8   9  10  11  12
  2 |       4   6   8  10  12  14  16  18  20  22  24
  3 |           9  12  15  18  21  24  27  30  33  36
  4 |              16  20  24  28  32  36  40  44  48
  5 |                  25  30  35  40  45  50  55  60
  6 |                      36  42  48  54  60  66  72
  7 |                          49  56  63  70  77  84
  8 |                              64  72  80  88  96
  9 |                                  81  90  99 108
 10 |                                     100 110 120
 11 |                                         121 132
 12 |                                             144

[edit] AutoIt

#AutoIt Version: 3.2.10.0
$tableupto=12
$table=""
for $i = 1 To $tableupto
for $j = $i to $tableupto
$prod=string($i*$j)
if StringLen($prod) == 1 then
$prod = " "& $prod
EndIf
if StringLen($prod) == 2 then
$prod = " "& $prod
EndIf
$table = $table&" "&$prod
Next
$table = $table&" - "&$i&@CRLF
for $k = 1 to $i
$table = $table&" "
Next
Next
msgbox(0,"Multiplication Tables",$table)

[edit] AWK

 
BEGIN{
for(i=1;i<13;i++){
for(j=1;j<13;j++){
if(j>=i||j==1){printf "%4d",i*j}
else {printf " "}
}
print
}
}
 
1 2 3 4 5 6 7 8 9 10 11 12
2 4 6 8 10 12 14 16 18 20 22 24
3 9 12 15 18 21 24 27 30 33 36
4 16 20 24 28 32 36 40 44 48
5 25 30 35 40 45 50 55 60
6 36 42 48 54 60 66 72
7 49 56 63 70 77 84
8 64 72 80 88 96
9 81 90 99 108
10 100 110 120
11 121 132
12 144
 

[edit] BASIC

Works with: QBasic
CLS
 
'header row
PRINT " ";
FOR n = 1 TO 12
'do it this way for alignment purposes
o$ = " "
MID$(o$, LEN(o$) - LEN(STR$(n)) + 1) = STR$(n)
PRINT o$;
NEXT
PRINT : PRINT " "; STRING$(49, "-");
 
FOR n = 1 TO 12
PRINT
IF n < 10 THEN PRINT " ";
PRINT n; "|"; 'row labels
FOR m = 1 TO n - 1
PRINT " ";
NEXT
FOR m = n TO 12
'alignment again
o$ = " "
MID$(o$, LEN(o$) - LEN(STR$(m * n)) + 1) = STR$(m * n)
PRINT o$;
NEXT
NEXT

Output:

       1   2   3   4   5   6   7   8   9  10  11  12
   -------------------------------------------------
 1 |   1   2   3   4   5   6   7   8   9  10  11  12
 2 |       4   6   8  10  12  14  16  18  20  22  24
 3 |           9  12  15  18  21  24  27  30  33  36
 4 |              16  20  24  28  32  36  40  44  48
 5 |                  25  30  35  40  45  50  55  60
 6 |                      36  42  48  54  60  66  72
 7 |                          49  56  63  70  77  84
 8 |                              64  72  80  88  96
 9 |                                  81  90  99 108
10 |                                     100 110 120
11 |                                         121 132
12 |                                             144

See also: BBC BASIC, Liberty BASIC, PureBasic

[edit] Applesoft BASIC

100 M = 12
110 DEF FN T(X) = X * 3 + (X < 4) * (4 - X) + (X > 10) * (X - 10) - 1
120 FOR N = -1 TO M
130 IF NOT N THEN PRINT CHR$(13) TAB(5); : FOR J = 5 TO FN T(M + 1) - 2 : PRINT "-"; : NEXT J, N
140 I = ABS(N)
150 IF N > 0 THEN PRINT CHR$(13) MID$(" ", 1, I < 10) I" !";
160 FOR J = I TO M
170 V$ = STR$(I * J)
180 PRINT TAB(FN T(J)) MID$(" ", 1, 3 - LEN(V$) - (J < 4)) V$;
190 NEXT J, N

[edit] BBC BASIC

BBC BASIC automatically right-justifies numeric output.

      @% = 5 : REM Set column width
FOR row% = 1 TO 12
PRINT row% TAB(row% * @%) ;
FOR col% = row% TO 12
PRINT row% * col% ;
NEXT col%
PRINT
NEXT row%

Output:

    1    1    2    3    4    5    6    7    8    9   10   11   12
    2         4    6    8   10   12   14   16   18   20   22   24
    3              9   12   15   18   21   24   27   30   33   36
    4                  16   20   24   28   32   36   40   44   48
    5                       25   30   35   40   45   50   55   60
    6                            36   42   48   54   60   66   72
    7                                 49   56   63   70   77   84
    8                                      64   72   80   88   96
    9                                           81   90   99  108
   10                                               100  110  120
   11                                                    121  132
   12                                                         144

[edit] Bracmat

  ( multiplicationTable
= high i j row row2 matrix padFnc tmp
, celPad leftCelPad padFnc celDashes leftDashes
.  !arg:?high
& ( padFnc
= L i w d
. @(!arg:? [?L)
& 1+(!L:?i):?L
& " ":?w
& "-":?d
& whl
' ( !i+-1:~<0:?i
& " " !w:?w
& "-" !d:?d
)
& str$!w:?w
& (
' (
. @(str$(rev$!arg ()$w):?arg [($L) ?)
& rev$!arg
)
. str$!d
)
)
& padFnc$(!high^2):((=?celPad).?celDashes)
& @(!high:?tmp [-2 ?)
& padFnc$!tmp:((=?leftCelPad).?leftDashes)
& 0:?i
& :?row:?row2
& whl
' ( 1+!i:~>!high:?i
& !row celPad$!i:?row
& !celDashes !row2:?row2
)
& str$(leftCelPad$X "|" !row \n !leftDashes "+" !row2 \n)
 : ?matrix
& 0:?j
& whl
' ( 1+!j:~>!high:?j
& 0:?i
& :?row
& whl
' ( 1+!i:<!j:?i
& celPad$() !row:?row
)
& leftCelPad$!j "|" !row:?row
& whl
' ( 1+!i:~>!high:?i
& !row celPad$(!i*!j):?row
)
& !matrix str$(!row \n):?matrix
)
& str$!matrix
)
& out$(multiplicationTable$12)
& done;

Output:

 X|   1   2   3   4   5   6   7   8   9  10  11  12
--+------------------------------------------------
 1|   1   2   3   4   5   6   7   8   9  10  11  12
 2|       4   6   8  10  12  14  16  18  20  22  24
 3|           9  12  15  18  21  24  27  30  33  36
 4|              16  20  24  28  32  36  40  44  48
 5|                  25  30  35  40  45  50  55  60
 6|                      36  42  48  54  60  66  72
 7|                          49  56  63  70  77  84
 8|                              64  72  80  88  96
 9|                                  81  90  99 108
10|                                     100 110 120
11|                                         121 132
12|                                             144

[edit] C

int main()
{
int i, j, n = 12;
 
for (j = 1; j <= n; j++) printf("%3d%c", j, j - n ? ' ':'\n');
for (j = 0; j <= n; j++) printf(j - n ? "----" : "+\n");
 
for (i = 1; i <= n; printf("| %d\n", i++))
for (j = 1; j <= n; j++)
printf(j < i ? " " : "%3d ", i * j);
 
return 0;
}
output
  1   2   3   4   5   6   7   8   9  10  11  12 
------------------------------------------------
1 2 3 4 5 6 7 8 9 10 11 12 | 1
4 6 8 10 12 14 16 18 20 22 24 | 2
9 12 15 18 21 24 27 30 33 36 | 3
16 20 24 28 32 36 40 44 48 | 4
25 30 35 40 45 50 55 60 | 5
36 42 48 54 60 66 72 | 6
49 56 63 70 77 84 | 7
64 72 80 88 96 | 8
81 90 99 108 | 9
100 110 120 | 10
121 132 | 11
144 | 12

[edit] C++

This is a slightly more-generalized version that takes any minimum and maximum table value, and formats the table columns.

#include <iostream>
#include <iomanip>
#include <cmath> // for log10()
#include <algorithm> // for max()
 
size_t get_table_column_width(const int min, const int max)
{
unsigned int abs_max = std::max(max*max, min*min);
 
// abs_max is the largest absolute value we might see.
// If we take the log10 and add one, we get the string width
// of the largest possible absolute value.
// Add one for a little whitespace guarantee.
size_t colwidth = 1 + std::log10(abs_max) + 1;
 
// If only one of them is less than 0, then some will
// be negative.
bool has_negative_result = (min < 0) && (max > 0);
 
// If some values may be negative, then we need to add some space
// for a sign indicator (-)
if(has_negative_result)
colwidth++;
 
return colwidth;
}
 
void print_table_header(const int min, const int max)
{
size_t colwidth = get_table_column_width(min, max);
 
// table corner
std::cout << std::setw(colwidth) << " ";
 
for(int col = min; col <= max; ++col)
{
std::cout << std::setw(colwidth) << col;
}
 
// End header with a newline and blank line.
std::cout << std::endl << std::endl;
}
 
void print_table_row(const int num, const int min, const int max)
{
size_t colwidth = get_table_column_width(min, max);
 
// Header column
std::cout << std::setw(colwidth) << num;
 
// Spacing to ensure only the top half is printed
for(int multiplicand = min; multiplicand < num; ++multiplicand)
{
std::cout << std::setw(colwidth) << " ";
}
 
// Remaining multiplicands for the row.
for(int multiplicand = num; multiplicand <= max; ++multiplicand)
{
std::cout << std::setw(colwidth) << num * multiplicand;
}
 
// End row with a newline and blank line.
std::cout << std::endl << std::endl;
}
 
void print_table(const int min, const int max)
{
// Header row
print_table_header(min, max);
 
// Table body
for(int row = min; row <= max; ++row)
{
print_table_row(row, min, max);
}
}
 
int main()
{
print_table(1, 12);
return 0;
}
 

Output:

       1   2   3   4   5   6   7   8   9  10  11  12

   1   1   2   3   4   5   6   7   8   9  10  11  12

   2       4   6   8  10  12  14  16  18  20  22  24

   3           9  12  15  18  21  24  27  30  33  36

   4              16  20  24  28  32  36  40  44  48

   5                  25  30  35  40  45  50  55  60

   6                      36  42  48  54  60  66  72

   7                          49  56  63  70  77  84

   8                              64  72  80  88  96

   9                                  81  90  99 108

  10                                     100 110 120

  11                                         121 132

  12                                             144

[edit] C#

using System;
 
namespace multtbl
{
class Program
{
static void Main(string[] args)
{
Console.Write(" X".PadRight(4));
for (int i = 1; i <= 12; i++)
Console.Write(i.ToString("####").PadLeft(4));
 
Console.WriteLine();
Console.Write(" ___");
 
for (int i = 1; i <= 12; i++)
Console.Write(" ___");
 
Console.WriteLine();
for (int row = 1; row <= 12; row++)
{
Console.Write(row.ToString("###").PadLeft(3).PadRight(4));
for (int col = 1; col <= 12; col++)
{
if (row <= col)
Console.Write((row * col).ToString("###").PadLeft(4));
else
Console.Write("".PadLeft(4));
}
 
Console.WriteLine();
}
 
Console.WriteLine();
Console.ReadLine();
}
}
}
 

Output:

 X     1   2   3   4   5   6   7   8   9  10  11  12
 ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___
  1    1   2   3   4   5   6   7   8   9  10  11  12
  2        4   6   8  10  12  14  16  18  20  22  24
  3            9  12  15  18  21  24  27  30  33  36
  4               16  20  24  28  32  36  40  44  48
  5                   25  30  35  40  45  50  55  60
  6                       36  42  48  54  60  66  72
  7                           49  56  63  70  77  84
  8                               64  72  80  88  96
  9                                   81  90  99 108
 10                                      100 110 120
 11                                          121 132
 12                                              144

[edit] Chef

Multigrain Bread.
 
Prints out a multiplication table.
 
Ingredients.
12 cups flour
12 cups grains
12 cups seeds
1 cup water
9 dashes yeast
1 cup nuts
40 ml honey
1 cup sugar
 
Method.
Sift the flour.
Put flour into the 1st mixing bowl.
Put yeast into the 1st mixing bowl.
Shake the flour until sifted.
Put grains into the 2nd mixing bowl.
Fold flour into the 2nd mixing bowl.
Put water into the 2nd mixing bowl.
Add yeast into the 2nd mixing bowl.
Combine flour into the 2nd mixing bowl.
Fold nuts into the 2nd mixing bowl.
Liquify nuts.
Put nuts into the 1st mixing bowl.
Pour contents of the 1st mixing bowl into the baking dish.
Sieve the flour.
Put yeast into the 2nd mixing bowl.
Add water into the 2nd mixing bowl.
Sprinkle the seeds.
Put flour into the 2nd mixing bowl.
Combine seeds into the 2nd mixing bowl.
Put yeast into the 2nd mixing bowl.
Put seeds into the 2nd mixing bowl.
Remove flour from the 2nd mixing bowl.
Fold honey into the 2nd mixing bowl.
Put water into the 2nd mixing bowl.
Fold sugar into the 2nd mixing bowl.
Squeeze the honey.
Put water into the 2nd mixing bowl.
Remove water from the 2nd mixing bowl.
Fold sugar into the 2nd mixing bowl.
Set aside.
Drip until squeezed.
Scoop the sugar.
Crush the seeds.
Put yeast into the 2nd mixing bowl.
Grind the seeds until crushed.
Put water into the 2nd mixing bowl.
Fold seeds into the 2nd mixing bowl.
Set aside.
Drop until scooped.
Randomize the seeds until sprinkled.
Fold honey into the 2nd mixing bowl.
Put flour into the 2nd mixing bowl.
Put grains into the 2nd mixing bowl.
Fold seeds into the 2nd mixing bowl.
Shake the flour until sieved.
Put yeast into the 2nd mixing bowl.
Add water into the 2nd mixing bowl.
Pour contents of the 2nd mixing bowl into the 2nd baking dish.
 
Serves 2.

Output:

  x    1   2   3   4   5   6   7   8   9  10  11  12
   1   1   2   3   4   5   6   7   8   9  10  11  12
   2       4   6   8  10  12  14  16  18  20  22  24
   3           9  12  15  18  21  24  27  30  33  36
   4              16  20  24  28  32  36  40  44  48
   5                  25  30  35  40  45  50  55  60
   6                      36  42  48  54  60  66  72
   7                          49  56  63  70  77  84
   8                              64  72  80  88  96
   9                                  81  90  99 108
  10                                     100 110 120
  11                                         121 132
  12                                             144

[edit] Clojure

This is more generalized. Any size can be used and the table will be formatted appropriately.

(let [size 12
trange (range 1 (inc size))
fmt-width (+ (.length (str (* size size))) 1)
fmt-str (partial format (str "%" fmt-width "s"))
fmt-dec (partial format (str "% " fmt-width "d"))]
 
(doseq [s (cons
(apply str (fmt-str " ") (map #(fmt-dec %) trange))
(for [i trange]
(apply str (fmt-dec i) (map #(fmt-str (str %))
(map #(if (>= % i) (* i %) " ")
(for [j trange] j))))))]
(println s)))
 

Output:

       1   2   3   4   5   6   7   8   9  10  11  12
   1   1   2   3   4   5   6   7   8   9  10  11  12
   2       4   6   8  10  12  14  16  18  20  22  24
   3           9  12  15  18  21  24  27  30  33  36
   4              16  20  24  28  32  36  40  44  48
   5                  25  30  35  40  45  50  55  60
   6                      36  42  48  54  60  66  72
   7                          49  56  63  70  77  84
   8                              64  72  80  88  96
   9                                  81  90  99 108
  10                                     100 110 120
  11                                         121 132
  12                                             144

[edit] CoffeeScript

 
print_multiplication_tables = (n) ->
width = 4
 
pad = (s, n=width, c=' ') ->
s = s.toString()
result = ''
padding = n - s.length
while result.length < padding
result += c
result + s
 
s = pad('') + '|'
for i in [1..n]
s += pad i
console.log s
 
s = pad('', width, '-') + '+'
for i in [1..n]
s += pad '', width, '-'
console.log s
 
 
for i in [1..n]
s = pad i
s += '|'
s += pad '', width*(i - 1)
for j in [i..n]
s += pad i*j
console.log s
 
print_multiplication_tables 12
 
 
 

output

 
> coffee multiply.coffee
| 1 2 3 4 5 6 7 8 9 10 11 12
----+------------------------------------------------
1| 1 2 3 4 5 6 7 8 9 10 11 12
2| 4 6 8 10 12 14 16 18 20 22 24
3| 9 12 15 18 21 24 27 30 33 36
4| 16 20 24 28 32 36 40 44 48
5| 25 30 35 40 45 50 55 60
6| 36 42 48 54 60 66 72
7| 49 56 63 70 77 84
8| 64 72 80 88 96
9| 81 90 99 108
10| 100 110 120
11| 121 132
12| 144
 

[edit] Common Lisp

 
(do ((m 0 (if (= 12 m) 0 (1+ m)))
(n 0 (if (= 12 m) (1+ n) n)))
((= n 13))
(if (zerop n)
(case m
(0 (format t " *|"))
(12 (format t " 12~&---+------------------------------------------------~&"))
(otherwise
(format t "~4,D" m)))
(case m
(0 (format t "~3,D|" n))
(12 (format t "~4,D~&" (* n m)))
(otherwise
(if (>= m n)
(format t "~4,D" (* m n))
(format t " "))))))
 

[edit] D

Translation of: PicoLisp
void main() {
import std.stdio, std.array, std.range, std.algorithm;
 
enum n = 12;
writefln("  %(%4d%)\n%s", iota(1, n+1), "-".replicate(4*n + 4));
foreach (immutable y; 1 .. n + 1)
writefln("%4d" ~ " ".replicate(4 * (y - 1)) ~ "%(%4d%)", y,
iota(y, n + 1).map!(x => x * y));
}
Output:
       1   2   3   4   5   6   7   8   9  10  11  12
----------------------------------------------------
   1   1   2   3   4   5   6   7   8   9  10  11  12
   2       4   6   8  10  12  14  16  18  20  22  24
   3           9  12  15  18  21  24  27  30  33  36
   4              16  20  24  28  32  36  40  44  48
   5                  25  30  35  40  45  50  55  60
   6                      36  42  48  54  60  66  72
   7                          49  56  63  70  77  84
   8                              64  72  80  88  96
   9                                  81  90  99 108
  10                                     100 110 120
  11                                         121 132
  12                                             144

[edit] Delphi

Translation of: DWScript
program MultiplicationTables;
 
{$APPTYPE CONSOLE}
 
uses SysUtils;
 
const
MAX_COUNT = 12;
var
lRow, lCol: Integer;
begin
Write(' | ');
for lRow := 1 to MAX_COUNT do
Write(Format('%4d', [lRow]));
Writeln('');
Writeln('--+-' + StringOfChar('-', MAX_COUNT * 4));
for lRow := 1 to MAX_COUNT do
begin
Write(Format('%2d', [lRow]));
Write('| ');
for lCol := 1 to MAX_COUNT do
begin
if lCol < lRow then
Write(' ')
else
Write(Format('%4d', [lRow * lCol]));
end;
Writeln;
end;
end.

[edit] DWScript

const size = 12;
var row, col : Integer;
 
Print(' | ');
for row:=1 to size do
Print(Format('%4d', [row]));
PrintLn('');
PrintLn('--+-'+StringOfChar('-', size*4));
for row:=1 to size do begin
Print(Format('%2d', [row]));
Print('| ');
for col:=1 to size do begin
if col<row then
Print(' ')
else Print(Format('%4d', [row*col]));
end;
PrintLn('');
end;
 

[edit] E

  def size := 12
println(`{|style="border-collapse: collapse; text-align: right;"`)
println(`|`)
for x in 1..size {
println(`|style="border-bottom: 1px solid black; " | $x`)
}
for y in 1..size {
println(`|-`)
println(`|style="border-right: 1px solid black;" | $y`)
for x in 1..size {
println(`| &nbsp;${if (x >= y) { x*y } else {""}}`)
}
}
println("|}")

Targets MediaWiki markup. Output:

1 2 3 4 5 6 7 8 9 10 11 12
1  1  2  3  4  5  6  7  8  9  10  11  12
2    4  6  8  10  12  14  16  18  20  22  24
3      9  12  15  18  21  24  27  30  33  36
4        16  20  24  28  32  36  40  44  48
5          25  30  35  40  45  50  55  60
6            36  42  48  54  60  66  72
7              49  56  63  70  77  84
8                64  72  80  88  96
9                  81  90  99  108
10                    100  110  120
11                      121  132
12                        144

[edit] Erlang

 
-module( multiplication_tables ).
 
-export( [print_upto/1, task/0, upto/1] ).
 
print_upto( N ) ->
Upto_tuples = [{X, {Y, Sum}} || {X, Y, Sum} <- upto(N)],
io:fwrite( " " ),
[io:fwrite( "~5B", [X]) || X <- lists:seq(1, N)],
io:nl(),
io:nl(),
[print_upto(X, proplists:get_all_values(X, Upto_tuples)) || X <- lists:seq(1, N)].
 
 
task() -> print_upto( 12 ).
 
upto( N ) -> [{X, Y, X*Y} || X <- lists:seq(1, N), Y <- lists:seq(1, N), Y >= X].
 
 
 
print_upto( N, Uptos ) ->
io:fwrite( "~2B", [N] ),
io:fwrite( "~*s", [5*(N - 1), " "] ),
[io:fwrite("~5B", [Sum]) || {_Y, Sum} <- Uptos],
io:nl().
 
Output:
25> multiplication_tables:task().
      1    2    3    4    5    6    7    8    9   10   11   12

 1    1    2    3    4    5    6    7    8    9   10   11   12
 2         4    6    8   10   12   14   16   18   20   22   24
 3              9   12   15   18   21   24   27   30   33   36
 4                  16   20   24   28   32   36   40   44   48
 5                       25   30   35   40   45   50   55   60
 6                            36   42   48   54   60   66   72
 7                                 49   56   63   70   77   84
 8                                      64   72   80   88   96
 9                                           81   90   99  108
10                                               100  110  120
11                                                    121  132
12                                                         144


[edit] Euphoria

puts(1," x")
for i = 1 to 12 do
printf(1," %3d",i)
end for
 
puts(1,'\n')
 
for i = 1 to 12 do
printf(1,"%2d",i)
for j = 1 to 12 do
if j<i then
puts(1," ")
else
printf(1," %3d",i*j)
end if
end for
puts(1,'\n')
end for

Output:

 x   1   2   3   4   5   6   7   8   9  10  11  12
 1   1   2   3   4   5   6   7   8   9  10  11  12
 2       4   6   8  10  12  14  16  18  20  22  24
 3           9  12  15  18  21  24  27  30  33  36
 4              16  20  24  28  32  36  40  44  48
 5                  25  30  35  40  45  50  55  60
 6                      36  42  48  54  60  66  72
 7                          49  56  63  70  77  84
 8                              64  72  80  88  96
 9                                  81  90  99 108
10                                     100 110 120
11                                         121 132
12                                             144

[edit] F#

Translation of C#

 
open System
 
let multTable () =
Console.Write (" X".PadRight (4))
for i = 1 to 12 do Console.Write ((i.ToString "####").PadLeft 4)
Console.Write "\n ___"
for i = 1 to 12 do Console.Write " ___"
Console.WriteLine ()
for row = 1 to 12 do
Console.Write (row.ToString("###").PadLeft(3).PadRight(4))
for col = 1 to 12 do
if row <= col then Console.Write ((row * col).ToString("###").PadLeft(4))
else
Console.Write ("".PadLeft 4)
Console.WriteLine ()
Console.WriteLine ()
Console.ReadKey () |> ignore
 
multTable ()
 

Output:

 X     1   2   3   4   5   6   7   8   9  10  11  12
 ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___
  1    1   2   3   4   5   6   7   8   9  10  11  12
  2        4   6   8  10  12  14  16  18  20  22  24
  3            9  12  15  18  21  24  27  30  33  36
  4               16  20  24  28  32  36  40  44  48
  5                   25  30  35  40  45  50  55  60
  6                       36  42  48  54  60  66  72
  7                           49  56  63  70  77  84
  8                               64  72  80  88  96
  9                                   81  90  99 108
 10                                      100 110 120
 11                                          121 132
 12                                              144

[edit] Factor

USING: io kernel math math.parser math.ranges sequences ;
IN: multiplication-table
 
: print-row ( n -- )
[ number>string 2 CHAR: space pad-head write " |" write ]
[ 1 - [ " " write ] times ]
[
dup 12 [a,b]
[ * number>string 4 CHAR: space pad-head write ] with each
] tri nl ;
 
: print-table ( -- )
" " write
1 12 [a,b] [ number>string 4 CHAR: space pad-head write ] each nl
" +" write
12 [ "----" write ] times nl
1 12 [a,b] [ print-row ] each ;
       1   2   3   4   5   6   7   8   9  10  11  12
   +------------------------------------------------
 1 |   1   2   3   4   5   6   7   8   9  10  11  12
 2 |       4   6   8  10  12  14  16  18  20  22  24
 3 |           9  12  15  18  21  24  27  30  33  36
 4 |              16  20  24  28  32  36  40  44  48
 5 |                  25  30  35  40  45  50  55  60
 6 |                      36  42  48  54  60  66  72
 7 |                          49  56  63  70  77  84
 8 |                              64  72  80  88  96
 9 |                                  81  90  99 108
10 |                                     100 110 120
11 |                                         121 132
12 |                                             144

[edit] FALSE

[$100\>[" "]?$10\>[" "]?." "]p:
[$p;! m: 2[$m;\>][" "1+]# [$13\>][$m;*p;!1+]#%"
"]l:
1[$13\>][$l;!1+]#%

[edit] Fantom

 
class Main
{
static Void multiplicationTable (Int n)
{
// print column headings
echo (" |" + (1..n).map |Int a -> Str| { a.toStr.padl(4)}.join("") )
echo ("-----" + (1..n).map { "----" }.join("") )
// work through each row
(1..n).each |i|
{
echo ( i.toStr.padl(4) + "|" +
Str.spaces(4*(i-1)) +
(i..n).map |Int j -> Str| { (i*j).toStr.padl(4)}.join("") )
}
}
 
public static Void main ()
{
multiplicationTable (12)
}
}
 

[edit] Forth

 
: multiplication-table
cr 2 spaces 13 2 do i 4 u.r loop
cr
13 2 do
cr i 2 u.r
13 2 do
i j < if 4 spaces else i j * 4 u.r then
loop
loop ;
 

[edit] Fortran

Works with: Fortran version 90 and later
program multtable
implicit none
 
integer :: i, j, k
 
write(*, "(a)") " x| 1 2 3 4 5 6 7 8 9 10 11 12"
write(*, "(a)") "--+------------------------------------------------"
do i = 1, 12
write(*, "(i2, a)", advance="no") i, "|"
do k = 2, i
write(*, "(a4)", advance="no") ""
end do
do j = i, 12
write(*, "(i4)", advance="no") i*j
end do
write(*, *)
end do
 
end program multtable

[edit] Go

 
package main
 
import (
"fmt"
)
 
func main() {
fmt.Print(" x |")
for i := 1; i <= 12; i++ {
fmt.Printf("%4d", i)
}
fmt.Print("\n---+")
for i := 1; i <= 12; i++ {
fmt.Print("----")
}
for j := 1; j <= 12; j++ {
fmt.Printf("\n%2d |", j)
for i := 1; i <= 12; i++ {
if i >= j {
fmt.Printf("%4d", i*j)
} else {
fmt.Print(" ")
}
}
}
fmt.Println("")
}
 

[edit] Groovy

Solution:

def printMultTable = { size = 12 ->
assert size > 1
 
// factor1 line
print ' |'; (1..size).each { f1 -> printf('%4d', f1) }; println ''
 
// dividing line
print '--+'; (1..size).each { printf('----', it) }; println ''
 
// factor2 result lines
(1..size).each { f2 ->
printf('%2d|', f2)
(1..<f2).each{ print ' ' }
(f2..size).each{ f1 -> printf('%4d', f1*f2) }
println ''
}
}
 
printMultTable()

Output:

  |   1   2   3   4   5   6   7   8   9  10  11  12
--+------------------------------------------------
 1|   1   2   3   4   5   6   7   8   9  10  11  12
 2|       4   6   8  10  12  14  16  18  20  22  24
 3|           9  12  15  18  21  24  27  30  33  36
 4|              16  20  24  28  32  36  40  44  48
 5|                  25  30  35  40  45  50  55  60
 6|                      36  42  48  54  60  66  72
 7|                          49  56  63  70  77  84
 8|                              64  72  80  88  96
 9|                                  81  90  99 108
10|                                     100 110 120
11|                                         121 132
12|                                             144

[edit] Haskell

import Control.Monad
import Text.Printf
 
main = do
putStrLn $ " x" ++ concatMap fmt [1..12]
zipWithM_ f [1..12] $ iterate (" " ++) ""
where f n s = putStrLn $ fmt n ++ s ++ concatMap (fmt . (*n)) [n..12]
fmt n = printf "%4d" (n :: Int)

[edit] HicEst

WRITE(Row=1) " x   1   2   3   4   5   6   7   8   9  10  11  12"
DO line = 1, 12
WRITE(Row=line+2, Format='i2') line
DO col = line, 12
WRITE(Row=line+2, Column=4*col, Format='i3') line*col
ENDDO
ENDDO

[edit] Icon and Unicon

procedure main()
lim := 13
wid := 5
every writes(right("* |" | (1 to lim) | "\n",wid)|right("\n",wid*(lim+1),"_")) # header row and separator
every (i := 1 to lim) &
writes(right( i||" |" | (j := 1 to lim, if j < i then "" else i*j) | "\n",wid)) # table content and triangle
end

The above example is a somewhat exaggerated example of contractions. In both cases 'every' is used to force all alternatives including row labels, column headings, content, line terminators. The upper triangle is produced by embedding an 'if' expression inside the object of an 'every' (normally an error prone construct which would malfunction if not carefully separated from the generators for 'i' and 'j' - an all too tempting possibility once you get into this mind set.)


Sample output:
 * |    1    2    3    4    5    6    7    8    9   10   11   12   13    
_____________________________________________________________________
  1 |    1    2    3    4    5    6    7    8    9   10   11   12   13    
  2 |         4    6    8   10   12   14   16   18   20   22   24   26    
  3 |              9   12   15   18   21   24   27   30   33   36   39    
  4 |                  16   20   24   28   32   36   40   44   48   52    
  5 |                       25   30   35   40   45   50   55   60   65    
  6 |                            36   42   48   54   60   66   72   78    
  7 |                                 49   56   63   70   77   84   91    
  8 |                                      64   72   80   88   96  104    
  9 |                                           81   90   99  108  117    
 10 |                                               100  110  120  130    
 11 |                                                    121  132  143    
 12 |                                                         144  156    
 13 |                                                              169 

[edit] J

   multtable=: <:/~ * */~
format=: 'b4.0' 8!:2 ]
(('*' ; ,.) ,. ({. ; ])@format@multtable) >:i.12
┌──┬────────────────────────────────────────────────┐
│* │ 1 2 3 4 5 6 7 8 9 10 11 12
├──┼────────────────────────────────────────────────┤
11 2 3 4 5 6 7 8 9 10 11 12
24 6 8 10 12 14 16 18 20 22 24
39 12 15 18 21 24 27 30 33 36
416 20 24 28 32 36 40 44 48
525 30 35 40 45 50 55 60
636 42 48 54 60 66 72
749 56 63 70 77 84
864 72 80 88 96
981 90 99 108
10100 110 120
11121 132
12144
└──┴────────────────────────────────────────────────┘

That said, note that */~ is the core primitive used to construct a multiplication table and this is a general technique so that, for example, +/~ would make an addition table. The rest is just to make it look pretty (and to blank out the lower triangle -- we use a less than or equal table (<:/~) to control that, and format zeros as spaces to blank them out).

[edit] Java

 
public class MulTable{
public static void main(String args[]){
int i,j;
for(i=1;i<=12;i++)
{
System.out.print("\t"+i);
}
 
System.out.println("");
for(i=0;i<100;i++)
System.out.print("-");
System.out.println("");
for(i=1;i<=12;i++){
System.out.print(""+i+"|");
for(j=1;j<=12;j++){
if(j<i)
System.out.print("\t");
else
System.out.print("\t"+i*j);
}
System.out.println("");
}
}
}
 

Output:

        1       2       3       4       5       6       7       8       9       10      11      12
----------------------------------------------------------------------------------------------------
1|      1       2       3       4       5       6       7       8       9       10      11      12
2|              4       6       8       10      12      14      16      18      20      22      24
3|                      9       12      15      18      21      24      27      30      33      36
4|                              16      20      24      28      32      36      40      44      48
5|                                      25      30      35      40      45      50      55      60
6|                                              36      42      48      54      60      66      72
7|                                                      49      56      63      70      77      84
8|                                                              64      72      80      88      96
9|                                                                      81      90      99      108
10|                                                                             100     110     120
11|                                                                                     121     132
12|                                                                                             144

[edit] JavaScript

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<title>12 times table</title>
<script type='text/javascript'>
 
function multiplication_table(n, target) {
var table = document.createElement('table');
 
var row = document.createElement('tr');
var cell = document.createElement('th');
cell.appendChild(document.createTextNode('x'));
row.appendChild(cell);
for (var x = 1; x <=n; x++) {
cell = document.createElement('th');
cell.appendChild(document.createTextNode(x));
row.appendChild(cell);
}
table.appendChild(row);
 
for (var x = 1; x <=n; x++) {
row = document.createElement('tr');
cell = document.createElement('th');
cell.appendChild(document.createTextNode(x));
row.appendChild(cell);
var y;
for (y = 1; y < x; y++) {
cell = document.createElement('td');
cell.appendChild(document.createTextNode('\u00a0'));
row.appendChild(cell);
}
for (; y <= n; y++) {
cell = document.createElement('td');
cell.appendChild(document.createTextNode(x*y));
row.appendChild(cell);
}
table.appendChild(row);
}
target.appendChild(table);
}
 
</script>
<style type='text/css'>
body {font-family: sans-serif;}
table {border-collapse: collapse;}
th, td {border: 1px solid black; text-align: right; width: 4ex;}
</style>
</head>
<body onload="multiplication_table(12, document.getElementById('target'));">
<div id='target'></div>
</body>
</html>

Outputs (minus the style):

x123456789101112
1123456789101112
2 4681012141618202224
3 9121518212427303336
4 162024283236404448
5 2530354045505560
6 36424854606672
7 495663707784
8 6472808896
9 819099108
10 100110120
11 121132
12 144


[edit] Lasso

define printTimesTables(max::integer) => {
local(result) = ``
local(padSize) = string(#max*#max)->size + 1
 
// Print header row
#result->append((' ' * #padSize) + '|')
loop(#max) => {
#result->append(loop_count->asString(-padding=#padSize))
}
#result->append("\n" + (`-` * #padSize) + '+' + (`-` * (#padSize * #max)))
 
with left in 1 to #max do {
// left column
#result->append("\n" + #left->asString(-padding=#padSize) + '|')
 
// Table results
with right in 1 to #max do {
#result->append(
#right < #left
 ? ' ' * #padSize
| (#left * #right)->asString(-padding=#padSize)
)
}
}
 
return #result
}
 
printTimesTables(12)
Output:
----+------------------------------------------------
   1|   1   2   3   4   5   6   7   8   9  10  11  12
   2|       4   6   8  10  12  14  16  18  20  22  24
   3|           9  12  15  18  21  24  27  30  33  36
   4|              16  20  24  28  32  36  40  44  48
   5|                  25  30  35  40  45  50  55  60
   6|                      36  42  48  54  60  66  72
   7|                          49  56  63  70  77  84
   8|                              64  72  80  88  96
   9|                                  81  90  99 108
  10|                                     100 110 120
  11|                                         121 132
  12|                                             144


[edit] Liberty BASIC

Print "  |    1    2    3    4    5    6    7    8    9   10   11   12"
Print "--+------------------------------------------------------------"
 
For i = 1 To 12
nums$ = Right$(" " + str$(i), 2) + "|"
For ii = 1 To 12
If i <= ii Then
If ii >= 1 Then
nums$ = nums$ + Left$(" ", (5 - Len(str$(i * ii))))
End If
nums$ = nums$ + str$(i * ii)
Else
nums$ = nums$ + " "
End If
Next ii
Print nums$
Next i

[edit]

Works with: UCB Logo
to mult.table :n
type "| | for [i 2 :n] [type form :i 4 0] (print)
(print)
for [i 2 :n] [
type form :i 2 0
for [j 2 :n] [
type ifelse :i > :j ["| |] [form :i*:j 4 0]
]
(print)
]
end
 
mult.table 12
 

[edit] Lua

io.write( "   |" )
for i = 1, 12 do
io.write( string.format( "%#5d", i ) )
end
io.write( "\n", string.rep( "-", 12*5+4 ), "\n" )
 
for i = 1, 12 do
io.write( string.format( "%#2d |", i ) )
 
for j = 1, 12 do
if j < i then
io.write( " " )
else
io.write( string.format( "%#5d", i*j ) )
end
end
io.write( "\n" )
end
   |    1    2    3    4    5    6    7    8    9   10   11   12
----------------------------------------------------------------
 1 |    1    2    3    4    5    6    7    8    9   10   11   12
 2 |         4    6    8   10   12   14   16   18   20   22   24
 3 |              9   12   15   18   21   24   27   30   33   36
 4 |                  16   20   24   28   32   36   40   44   48
 5 |                       25   30   35   40   45   50   55   60
 6 |                            36   42   48   54   60   66   72
 7 |                                 49   56   63   70   77   84
 8 |                                      64   72   80   88   96
 9 |                                           81   90   99  108
10 |                                               100  110  120
11 |                                                    121  132
12 |                                                         144

[edit] Mathematica

Grid[{{Range[12]//Column,Grid[UpperTriangularize[KroneckerProduct[Range[12],Range[12]]]/.{0->""}]}}]

Output:

 
1 1	2	3	4	5	6	7	8	9	10	11	12
2	4	6	8	10	12	14	16	18	20	22	24
3		9	12	15	18	21	24	27	30	33	36
4			16	20	24	28	32	36	40	44	48
5				25	30	35	40	45	50	55	60
6					36	42	48	54	60	66	72
7						49	56	63	70	77	84
8							64	72	80	88	96
9								81	90	99	108
10									100	110	120
11										121	132
12											144

[edit] MATLAB / Octave

timesTable.m: (creates Times Table of N degree)

function table = timesTable(N)
table = [(0:N); (1:N)' triu( kron((1:N),(1:N)') )];
end

A minimally vectorized version of the above code:

function table = timesTable(N)
 
%Generates a column vector with integers from 1 to N
rowLabels = (1:N)';
 
%Generate a row vector with integers from 0 to N
columnLabels = (0:N);
 
%Generate the multiplication table using the kronecker tensor product
%of two vectors one a column vector and the other a row vector
table = kron((1:N),(1:N)');
 
%Make it upper triangular and concatenate the rowLabels and
%columnLabels to the table
table = [columnLabels; rowLabels triu(table)];
 
end


For N=12 the output is:

timesTable(12)
 
ans =
 
0 1 2 3 4 5 6 7 8 9 10 11 12
1 1 2 3 4 5 6 7 8 9 10 11 12
2 0 4 6 8 10 12 14 16 18 20 22 24
3 0 0 9 12 15 18 21 24 27 30 33 36
4 0 0 0 16 20 24 28 32 36 40 44 48
5 0 0 0 0 25 30 35 40 45 50 55 60
6 0 0 0 0 0 36 42 48 54 60 66 72
7 0 0 0 0 0 0 49 56 63 70 77 84
8 0 0 0 0 0 0 0 64 72 80 88 96
9 0 0 0 0 0 0 0 0 81 90 99 108
10 0 0 0 0 0 0 0 0 0 100 110 120
11 0 0 0 0 0 0 0 0 0 0 121 132
12 0 0 0 0 0 0 0 0 0 0 0 144
 

[edit] Maxima

for i: 1 thru 12 do (
for j: 1 thru 12 do (
if j>=i or j=1 then printf(true, "~4d", i*j) else printf(true, " ")
),
printf(true, "~%")
);

[edit] МК-61/52

П0	КИП0	КИП4	КИП5	ИП4	ИП5	*	С/П
ИП5 ИП0 - x=0 03
ИП4 ИП0 - x#0 22 ИП4 П5 БП 02
С/П

Input: 12 С/П ...

Output (compiled):

   1   2   3   4   5   6   7   8   9  10  11  12
       4   6   8  10  12  14  16  18  20  22  24
           9  12  15  18  21  24  27  30  33  36
              16  20  24  28  32  36  40  44  48
                  25  30  35  40  45  50  55  60
                      36  42  48  54  60  66  72
                          49  56  63  70  77  84
                              64  72  80  88  96
                                  81  90  99 108
                                     100 110 120
                                         121 132
                                             144

[edit] MUMPS

MULTTABLE(SIZE)
 ;Print out a multiplication table
 ;SIZE is the size of the multiplication table to make
 ;MW is the maximum width of the numbers
 ;D is the down axis
 ;A is the across axis
 ;BAR is the horizontal bar under the operands
NEW MW,D,A,BAR
IF $DATA(SIZE)<1 SET SIZE=12
SET MW=$LENGTH(SIZE*SIZE)
SET BAR="" FOR I=1:1:(MW+2) SET BAR=BAR_"-"
FOR D=1:1:(SIZE+2) DO
.FOR A=1:1:(SIZE+1) DO
..WRITE:(D=1)&(A=1) !,$JUSTIFY("",MW-1)," X|"
..WRITE:(D=1)&(A>1) ?((A-1)*5),$JUSTIFY((A-1),MW)
..WRITE:(D=2)&(A=1) !,BAR
..WRITE:(D=2)&(A'=1) BAR
..WRITE:(D>2)&(A=1) !,$JUSTIFY((D-2),MW)," |"
..WRITE:((A-1)>=(D-2))&((D-2)>=1) ?((A-1)*5),$JUSTIFY((D-2)*(A-1),MW)
KILL MW,D,A,BAR
QUIT
Output:
USER>D MULTTABLE^ROSETTA
 
   X|  1    2    3    4    5    6    7    8    9   10   11   12
-----------------------------------------------------------------
  1 |  1    2    3    4    5    6    7    8    9   10   11   12
  2 |       4    6    8   10   12   14   16   18   20   22   24
  3 |            9   12   15   18   21   24   27   30   33   36
  4 |                16   20   24   28   32   36   40   44   48
  5 |                     25   30   35   40   45   50   55   60
  6 |                          36   42   48   54   60   66   72
  7 |                               49   56   63   70   77   84
  8 |                                    64   72   80   88   96
  9 |                                         81   90   99  108
 10 |                                             100  110  120
 11 |                                                  121  132
 12 |                                                       144

[edit] MOO

This quick example is designed to demonstrate raw MOO. In other words it does not use any of the helper functions available in popular DBs such as LambdaMOO.

 
@verb me:@tables none none none rxd
@program me:@tables
player:tell(" | 1 2 3 4 5 6 7 8 9 10 11 12");
player:tell("-------------------------------------------------------------------");
for i in [1..12]
line = ((i < 10) ? " " | " ") + tostr(i) + " | ";
for j in [1..12]
if (j >= i)
product = i * j;
"calculate spacing for right justification of values";
if (product >= 100)
spacer = "";
elseif (product >= 10)
spacer = " ";
else
spacer = " ";
endif
line = line + " " + spacer + tostr(product);
else
line = line + " ";
endif
endfor
player:tell(line);
endfor
.
 

LambdaMOO string utilities version:

 
@program me:@tables
player:tell(" | 1 2 3 4 5 6 7 8 9 10 11 12");
player:tell($string_utils:space(67, "-"));
for i in [1..12]
line = " " + $string_utils:right(i, 2) + " | ";
for j in [1..12]
line = line + " " + ((i > j) ? " " | $string_utils:right(j*i, 3));
endfor
player:tell(line);
endfor
.
 

Output:

@tables
    |      1    2    3    4    5    6    7    8    9   10   11   12
-------------------------------------------------------------------
  1 |      1    2    3    4    5    6    7    8    9   10   11   12
  2 |           4    6    8   10   12   14   16   18   20   22   24
  3 |                9   12   15   18   21   24   27   30   33   36
  4 |                    16   20   24   28   32   36   40   44   48
  5 |                         25   30   35   40   45   50   55   60
  6 |                              36   42   48   54   60   66   72
  7 |                                   49   56   63   70   77   84
  8 |                                        64   72   80   88   96
  9 |                                             81   90   99  108
 10 |                                                 100  110  120
 11 |                                                      121  132
 12 |                                                           144

[edit] OCaml

Translation of: C
let () =
let max = 12 in
let fmax = float_of_int max in
 
let dgts = int_of_float (ceil (log10 (fmax *. fmax))) in
let fmt = Printf.printf " %*d" dgts in
let fmt2 = Printf.printf "%*s%c" dgts in
 
fmt2 "" 'x';
for i = 1 to max do fmt i done;
print_string "\n\n";
 
for j = 1 to max do
fmt j;
for i = 1 to pred j do fmt2 "" ' '; done;
for i = j to max do fmt (i*j); done;
print_newline()
done;
print_newline()

[edit] PARI/GP

Quick and dirty one-liner:

for(y=1,12,printf("%2Ps| ",y);for(x=1,12,print1(if(y>x,"",x*y)"\t"));print)

[edit] Pascal

See Delphi

[edit] Perl

our $max = 12;
our $width = length($max**2) + 1;
 
printf "%*s", $width, $_ foreach 'x|', 1..$max;
print "\n", '-' x ($width - 1), '+', '-' x ($max*$width), "\n";
foreach my $i (1..$max) {
printf "%*s", $width, $_
foreach "$i|", map { $_ >= $i and $_*$i } 1..$max;
print "\n";
}

Output:

  x|   1   2   3   4   5   6   7   8   9  10  11  12
---+------------------------------------------------
  1|   1   2   3   4   5   6   7   8   9  10  11  12
  2|       4   6   8  10  12  14  16  18  20  22  24
  3|           9  12  15  18  21  24  27  30  33  36
  4|              16  20  24  28  32  36  40  44  48
  5|                  25  30  35  40  45  50  55  60
  6|                      36  42  48  54  60  66  72
  7|                          49  56  63  70  77  84
  8|                              64  72  80  88  96
  9|                                  81  90  99 108
 10|                                     100 110 120
 11|                                         121 132
 12|                                             144

[edit] Perl 6

Translation of: Perl
Works with: Rakudo Star version 2010.08
my $max = 12;
my $width = chars $max**2;
my $f = "%{$width}s";
 
say 'x'.fmt($f), '┃ ', (1..$max).fmt($f);
say '━' x $width, '╋', '━' x $max*$width + $max;
for 1..$max -> $i {
say $i.fmt($f), '┃ ', (
for 1..$max -> $j {
$i <= $j ?? $i*$j !! '';
}
).fmt($f);
}

Output:

  x┃   1   2   3   4   5   6   7   8   9  10  11  12
━━━╋━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  1┃   1   2   3   4   5   6   7   8   9  10  11  12
  2┃       4   6   8  10  12  14  16  18  20  22  24
  3┃           9  12  15  18  21  24  27  30  33  36
  4┃              16  20  24  28  32  36  40  44  48
  5┃                  25  30  35  40  45  50  55  60
  6┃                      36  42  48  54  60  66  72
  7┃                          49  56  63  70  77  84
  8┃                              64  72  80  88  96
  9┃                                  81  90  99 108
 10┃                                     100 110 120
 11┃                                         121 132
 12┃                                             144

[edit] PL/I

 
/* 12 x 12 multiplication table. */
 
multiplication_table: procedure options (main);
declare (i, j) fixed decimal (2);
 
put skip edit ((i do i = 1 to 12)) (X(4), 12 F(4));
put skip edit ( (49)'_') (X(3), A);
 
do i = 1 to 12;
put skip edit (i, ' |', (i*j do j = i to 12))
(F(2), a, col(i*4+1), 12 F(4));
end;
 
end multiplication_table;
 

Result:

 
1 2 3 4 5 6 7 8 9 10 11 12
_________________________________________________
1 | 1 2 3 4 5 6 7 8 9 10 11 12
2 | 4 6 8 10 12 14 16 18 20 22 24
3 | 9 12 15 18 21 24 27 30 33 36
4 | 16 20 24 28 32 36 40 44 48
5 | 25 30 35 40 45 50 55 60
6 | 36 42 48 54 60 66 72
7 | 49 56 63 70 77 84
8 | 64 72 80 88 96
9 | 81 90 99 108
10 | 100 110 120
11 | 121 132
12 | 144
 

[edit] PicoLisp

sp>(de mulTable (N)
(space 4)
(for X N
(prin (align 4 X)) )
(prinl)
(prinl)
(for Y N
(prin (align 4 Y))
(space (* (dec Y) 4))
(for (X Y (>= N X) (inc X))
(prin (align 4 (* X Y))) )
(prinl) ) )
 
(mulTable 12)

Output:

       1   2   3   4   5   6   7   8   9  10  11  12

   1   1   2   3   4   5   6   7   8   9  10  11  12
   2       4   6   8  10  12  14  16  18  20  22  24
   3           9  12  15  18  21  24  27  30  33  36
   4              16  20  24  28  32  36  40  44  48
   5                  25  30  35  40  45  50  55  60
   6                      36  42  48  54  60  66  72
   7                          49  56  63  70  77  84
   8                              64  72  80  88  96
   9                                  81  90  99 108
  10                                     100 110 120
  11                                         121 132
  12                                             144

[edit] PureBasic

Procedure PrintMultiplicationTable(maxx, maxy)
sp = Len(Str(maxx*maxy)) + 1
trenner$ = "+"
For l1 = 1 To maxx + 1
For l2 = 1 To sp
trenner$ + "-"
Next
trenner$ + "+"
Next
header$ = "|" + RSet("x", sp) + "|"
For a = 1 To maxx
header$ + RSet(Str(a), sp)
header$ + "|"
Next
PrintN(trenner$)
PrintN(header$)
PrintN(trenner$)
For y = 1 To maxy
line$ = "|" + RSet(Str(y), sp) + "|"
For x = 1 To maxx
If x >= y
line$ + RSet(Str(x*y), sp)
Else
line$ + Space(sp)
EndIf
line$ + "|"
Next
PrintN(line$)
Next
PrintN(trenner$)
EndProcedure
 
OpenConsole()
PrintMultiplicationTable(12, 12)
Input()

Ouput similar to ALGOL 68

[edit] Python

>>> size = 12
>>> width = len(str(size**2))
>>> for row in range(-1,size+1):
if row==0:
print("─"*width + "┼"+"─"*((width+1)*size-1))
else:
print("".join("%*s%1s" % ((width,) + (("x","│") if row==-1 and col==0
else (row,"│") if row>0 and col==0
else (col,"") if row==-1
else ("","") if row>col
else (row*col,"")))
for col in range(size+1)))
 
 
x│ 1 2 3 4 5 6 7 8 9 10 11 12
───┼───────────────────────────────────────────────
11 2 3 4 5 6 7 8 9 10 11 12
24 6 8 10 12 14 16 18 20 22 24
39 12 15 18 21 24 27 30 33 36
416 20 24 28 32 36 40 44 48
525 30 35 40 45 50 55 60
636 42 48 54 60 66 72
749 56 63 70 77 84
864 72 80 88 96
981 90 99 108
10100 110 120
11121 132
12144
>>>

The above works with Python 3.X, which uses Unicode strings by default.
Declaring a file type of UTF-8 and adding a u to all string literals to transform them into Unicode literals would make the above work in Python 2.X. (As would using ASCII minus, plus, and pipe characters: "-", "+", "|"; instead of the non-ASCII chars used to draw a frame).

[edit] R

An ugly one line solution:

 
upper.tri(1:12 %o% 1:12, diag = TRUE) * 1:12 %o% 1:12
 

... and a much prettier one:

 
multiplication_table <- function(n=12)
{
one_to_n <- 1:n
x <- matrix(one_to_n) %*% t(one_to_n)
x[lower.tri(x)] <- 0
rownames(x) <- colnames(x) <- one_to_n
print(as.table(x), zero.print="")
invisible(x)
}
multiplication_table()
 

[edit] Racket

 
#lang racket
 
(define (show-line xs)
(for ([x xs]) (display (~a x #:width 4 #:align 'right)))
(newline))
 
(show-line (cons "" (range 1 13)))
(for ([y (in-range 1 13)])
(show-line (cons y (for/list ([x (in-range 1 13)])
(if (<= y x) (* x y) "")))))
 

Output:

       1   2   3   4   5   6   7   8   9  10  11  12
   1   1   2   3   4   5   6   7   8   9  10  11  12
   2       4   6   8  10  12  14  16  18  20  22  24
   3           9  12  15  18  21  24  27  30  33  36
   4              16  20  24  28  32  36  40  44  48
   5                  25  30  35  40  45  50  55  60
   6                      36  42  48  54  60  66  72
   7                          49  56  63  70  77  84
   8                              64  72  80  88  96
   9                                  81  90  99 108
  10                                     100 110 120
  11                                         121 132
  12                                             144

[edit] REBOL

rebol [
Title: "12x12 Multiplication Table"
Author: oofoe
Date: 2009-12-26
URL: http://rosettacode.org/wiki/Print_a_Multiplication_Table
]

 
size: 12
 
; Because of REBOL's GUI focus, it doesn't really do pictured output,
; so I roll my own. See Formatted_Numeric_Output for more
; comprehensive version:
 
pad: func [pad n][
n: to-string n
insert/dup n " " (pad - length? n)
n
]
p3: func [v][pad 3 v] ; A shortcut, I hate to type...
 
--: has [x][repeat x size + 1 [prin "+---"] print "+"] ; Special chars OK.
 
.row: func [label y /local row x][
row: reduce ["|" label "|"]
repeat x size [append row reduce [either x < y [" "][p3 x * y] "|"]]
print rejoin row
]
 
-- .row " x " 1 -- repeat y size [.row p3 y y] --
 
print rejoin [ crlf "What about " size: 5 "?" crlf ]
-- .row " x " 1 -- repeat y size [.row p3 y y] --
 
print rejoin [ crlf "How about " size: 20 "?" crlf ]
-- .row " x " 1 -- repeat y size [.row p3 y y] --

Output (only 12x12 shown):

+---+---+---+---+---+---+---+---+---+---+---+---+---+
| x |  1|  2|  3|  4|  5|  6|  7|  8|  9| 10| 11| 12|
+---+---+---+---+---+---+---+---+---+---+---+---+---+
|  1|  1|  2|  3|  4|  5|  6|  7|  8|  9| 10| 11| 12|
|  2|   |  4|  6|  8| 10| 12| 14| 16| 18| 20| 22| 24|
|  3|   |   |  9| 12| 15| 18| 21| 24| 27| 30| 33| 36|
|  4|   |   |   | 16| 20| 24| 28| 32| 36| 40| 44| 48|
|  5|   |   |   |   | 25| 30| 35| 40| 45| 50| 55| 60|
|  6|   |   |   |   |   | 36| 42| 48| 54| 60| 66| 72|
|  7|   |   |   |   |   |   | 49| 56| 63| 70| 77| 84|
|  8|   |   |   |   |   |   |   | 64| 72| 80| 88| 96|
|  9|   |   |   |   |   |   |   |   | 81| 90| 99|108|
| 10|   |   |   |   |   |   |   |   |   |100|110|120|
| 11|   |   |   |   |   |   |   |   |   |   |121|132|
| 12|   |   |   |   |   |   |   |   |   |   |   |144|
+---+---+---+---+---+---+---+---+---+---+---+---+---+

[edit] REXX

/*REXX program displays a  12x12  multiplication boxed grid table, grid */
/* will be displayed in "boxing" characters for ASCII or EBCDIC.*/
parse arg high . /*get optional grid size. */
if high=='' then high=12 /*not specified? Use default. */
ebcdic='f0'==1 /*is this an EBCDIC machine? */
 
if ebcdic then do /*══════════EBCDIC═══════════════*/
bar='fa'x /*vertical bar. */
dash='bf'x /*horizontal dash. */
bj ='cb'x /*bottom junction. */
tj ='cc'x /* top junction. */
cj ='8f'x /*center junction (cross). */
lj ='eb'x /* left junction. */
rj ='ec'x /* right junction. */
tlc='ac'x /*top left corner. */
trc='bc'x /*top right corner. */
blc='ab'x /*bottom left corner. */
brc='bb'x /*bottom right corner. */
end
else do /*══════════ASCII════════════════*/
bar='b3'x /*vertical bar. */
dash='c4'x /*horizontal dash. */
bj ='c1'x /*bottom junction. */
tj ='c2'x /* top junction. */
cj ='c5'x /*center junction (cross). */
lj ='c3'x /* left junction. */
rj ='b4'x /* right junction. */
tlc='da'x /*top left corner. */
trc='bf'x /*top right corner. */
blc='c0'x /*bottom left corner. */
brc='d9'x /*bottom right corner. */
end
 
cell=cj || copies(dash,5) /*define the top of the cell. */
sep=copies(cell,high+1)rj /*build the table separator. */
sepL=length(sep) /*length of separator line. */
width=length(cell)-1 /*width of the table cells. */
size=width-1 /*width for table numbers. */
box.=left('',width) /*construct all the cells. */
 
do j=0 to high /*step through zero to H (12). */
_=right(j,size-1)'x ' /*build "label"/border number. */
box.0.j=_ /*build top label cell. */
box.j.0=_ /*build left label cell. */
end /*j*/
 
box.0.0=centre('times',width) /*redefine box.0.0 with 'X'. */
 
do row=1 for high /*step through 1 to H (12). */
do col=row to high /*step through row to H (12). */
box.row.col=right(row*col,size)' ' /*build a mult. cell. */
end /*col*/
end /*row*/
 
do row=0 to high /*step through all the lines. */
asep=sep /*allow use of a modified sep. */
if row==0 then do
asep=overlay(tlc,asep,1) /*make a better tlc. */
asep=overlay(trc,asep,sepL) /*make a better trc. */
asep=translate(asep,tj,cj) /*make a better tj. */
end
else asep=overlay(lj,asep,1) /*make a better lj. */
 
say asep /*display a table grid line. */
if row==0 then call buildLine 00 /*display a blank grid line. */
call buildLine row /*build one line of the grid. */
if row==0 then call buildLine 00 /*display a blank grid line. */
end /*row*/
 
asep=sep /*allow use of a modified sep. */
asep=overlay(blc,asep,1) /*make a better bot left corner.*/
asep=overlay(brc,asep,sepL) /*make a better bot right corner.*/
asep=translate(asep,bj,cj) /*make a better bot junction. */
say asep /*display a table grid line. */
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────BUILDLINE subroutine────────────────*/
buildLine: w=; parse arg arow /*start with a blank cell. */
 
do col=0 to high /*step through 0 to H (12). */
w=w||bar||box.arow.col /*build one cell at a time. */
end /*col*/
say w || bar /*finish building the last cell. */
return

output

┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐
│     │     │     │     │     │     │     │     │     │     │     │     │     │
│times│  1x │  2x │  3x │  4x │  5x │  6x │  7x │  8x │  9x │ 10x │ 11x │ 12x │
│     │     │     │     │     │     │     │     │     │     │     │     │     │
├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│  1x │   1 │   2 │   3 │   4 │   5 │   6 │   7 │   8 │   9 │  10 │  11 │  12 │
├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│  2x │     │   4 │   6 │   8 │  10 │  12 │  14 │  16 │  18 │  20 │  22 │  24 │
├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│  3x │     │     │   9 │  12 │  15 │  18 │  21 │  24 │  27 │  30 │  33 │  36 │
├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│  4x │     │     │     │  16 │  20 │  24 │  28 │  32 │  36 │  40 │  44 │  48 │
├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│  5x │     │     │     │     │  25 │  30 │  35 │  40 │  45 │  50 │  55 │  60 │
├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│  6x │     │     │     │     │     │  36 │  42 │  48 │  54 │  60 │  66 │  72 │
├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│  7x │     │     │     │     │     │     │  49 │  56 │  63 │  70 │  77 │  84 │
├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│  8x │     │     │     │     │     │     │     │  64 │  72 │  80 │  88 │  96 │
├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│  9x │     │     │     │     │     │     │     │     │  81 │  90 │  99 │ 108 │
├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│ 10x │     │     │     │     │     │     │     │     │     │ 100 │ 110 │ 120 │
├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│ 11x │     │     │     │     │     │     │     │     │     │     │ 121 │ 132 │
├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│ 12x │     │     │     │     │     │     │     │     │     │     │     │ 144 │
└─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘

output when the following is used for input: 10

┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐
│     │     │     │     │     │     │     │     │     │     │     │
│times│  1x │  2x │  3x │  4x │  5x │  6x │  7x │  8x │  9x │ 10x │
│     │     │     │     │     │     │     │     │     │     │     │
├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│  1x │   1 │   2 │   3 │   4 │   5 │   6 │   7 │   8 │   9 │  10 │
├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│  2x │     │   4 │   6 │   8 │  10 │  12 │  14 │  16 │  18 │  20 │
├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│  3x │     │     │   9 │  12 │  15 │  18 │  21 │  24 │  27 │  30 │
├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│  4x │     │     │     │  16 │  20 │  24 │  28 │  32 │  36 │  40 │
├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│  5x │     │     │     │     │  25 │  30 │  35 │  40 │  45 │  50 │
├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│  6x │     │     │     │     │     │  36 │  42 │  48 │  54 │  60 │
├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│  7x │     │     │     │     │     │     │  49 │  56 │  63 │  70 │
├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│  8x │     │     │     │     │     │     │     │  64 │  72 │  80 │
├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│  9x │     │     │     │     │     │     │     │     │  81 │  90 │
├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│ 10x │     │     │     │     │     │     │     │     │     │ 100 │
└─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘

[edit] Ruby

def multiplication_table(n)
puts " " + ((" %3d" * n) % (1..n).to_a)
1.upto(n) do |x|
print "%3d " % x
1.upto(x-1) {|y| print " "}
x.upto(n) {|y| print " %3d" % (x*y)}
puts ""
end
end
 
multiplication_table 12

[edit] Scheme

A better implementation of iota is provided by SRFI-1 [1].

 
(define iota
(lambda (count start step)
(let loop ((result (list (+ start (* (- count 1) step)))))
(let ((acc (car result)))
(if (= acc start)
result
(loop (cons (- acc step) result)))))))
 
 
(define table
(lambda (x)
(let loop ((count 1)
(numbers (iota x 1 1)))
(if (not (null? numbers))
(begin
(display (make-string (* 6 (- count 1)) #\space))
(for-each
(lambda (n)
(let ((number (number->string (* n count))))
(display (string-append
(make-string (- 6 (string-length number)) #\space)
number))))
numbers)
(newline)
(loop (+ count 1)
(cdr numbers)))))))
 
(table 12)
     1     2     3     4     5     6     7     8     9    10    11    12
           4     6     8    10    12    14    16    18    20    22    24
                 9    12    15    18    21    24    27    30    33    36
                      16    20    24    28    32    36    40    44    48
                            25    30    35    40    45    50    55    60
                                  36    42    48    54    60    66    72
                                        49    56    63    70    77    84
                                              64    72    80    88    96
                                                    81    90    99   108
                                                         100   110   120
                                                               121   132
                                                                     144

[edit] Seed7

$ include "seed7_05.s7i";
 
const proc: main is func
local
const integer: n is 12;
var integer: i is 0;
var integer: j is 0;
begin
for j range 1 to n do
write(j lpad 3 <& " ");
end for;
writeln;
writeln("-" mult 4 * n);
for i range 1 to n do
for j range 1 to n do
if j < i then
write(" ");
else
write(i * j lpad 3 <& " ");
end if;
end for;
writeln("|" <& i lpad 3);
end for;
end func;

Output:

  1   2   3   4   5   6   7   8   9  10  11  12 
------------------------------------------------
  1   2   3   4   5   6   7   8   9  10  11  12 |  1
      4   6   8  10  12  14  16  18  20  22  24 |  2
          9  12  15  18  21  24  27  30  33  36 |  3
             16  20  24  28  32  36  40  44  48 |  4
                 25  30  35  40  45  50  55  60 |  5
                     36  42  48  54  60  66  72 |  6
                         49  56  63  70  77  84 |  7
                             64  72  80  88  96 |  8
                                 81  90  99 108 |  9
                                    100 110 120 | 10
                                        121 132 | 11
                                            144 | 12

[edit] Tcl

puts "  x\u2502   1   2   3   4   5   6   7   8   9  10  11  12"
puts \u0020\u2500\u2500\u253c[string repeat \u2500 48]
for {set i 1} {$i <= 12} {incr i} {
puts -nonewline [format "%3d" $i]\u2502[string repeat " " [expr {$i*4-4}]]
for {set j 1} {$j <= 12} {incr j} {
if {$j >= $i} {
puts -nonewline [format "%4d" [expr {$i*$j}]]
}
}
puts ""
}

Output:

  x│   1   2   3   4   5   6   7   8   9  10  11  12
 ──┼────────────────────────────────────────────────
  1│   1   2   3   4   5   6   7   8   9  10  11  12
  2│       4   6   8  10  12  14  16  18  20  22  24
  3│           9  12  15  18  21  24  27  30  33  36
  4│              16  20  24  28  32  36  40  44  48
  5│                  25  30  35  40  45  50  55  60
  6│                      36  42  48  54  60  66  72
  7│                          49  56  63  70  77  84
  8│                              64  72  80  88  96
  9│                                  81  90  99 108
 10│                                     100 110 120
 11│                                         121 132
 12│                                             144

[edit] TUSCRIPT

 
$$ MODE TUSCRIPT
x=y="1'2'3'4'5'6'7'8'9'10'11'12"
LOOP n,col=x,cnt=""
skip=n-1
LOOP m,row=y
IF (m==skip) THEN
td=""
ELSE
td=col*row
coleqrow=col*n
IF (td.lt.#coleqrow) td=""
ENDIF
td=CENTER (td,+3," ")
cnt=APPEND (cnt,td," ")
ENDLOOP
col=CENTER (col,+3," ")
PRINT col,cnt
ENDLOOP
 

Output:

  1   2   3   4   5   6   7   8   9  10  11  12
  2   4   6   8  10  12  14  16  18  20  22  24
  3       9  12  15  18  21  24  27  30  33  36
  4          16  20  24  28  32  36  40  44  48
  5              25  30  35  40  45  50  55  60
  6                  36  42  48  54  60  66  72
  7                      49  56  63  70  77  84
  8                          64  72  80  88  96
  9                              81  90  99 108
 10                                 100 110 120
 11                                     121 132
 12                                         144

[edit] Ursala

It's no more difficult to express the general case than the size 12 case, so a table generating function parameterized by the size is used.

 
#import std
#import nat
 
table "n" =
 
~&plrTS(
~&xS pad` @xS <'x ','--'>-- --' | '*hS %nP* nrange/1 "n",
^CthPiC(`-!*h,~&) mat` *xSSK7 pad` *K7ihxPBSS (~&i&& %nP)** nleq&&product**iiK0lK2x nrange/1 "n")
 
#show+
 
main = table 12
 

A better way of using Ursala to make tables would be with the tbl library included with the standard package, which can generate LaTeX code for arbitrary heading hierarchies and typesetting options, but here it is in ASCII art.

  x  1 2 3  4  5  6  7  8  9  10  11  12
   -------------------------------------
 1 | 1 2 3  4  5  6  7  8  9  10  11  12
 2 |   4 6  8 10 12 14 16 18  20  22  24
 3 |     9 12 15 18 21 24 27  30  33  36
 4 |       16 20 24 28 32 36  40  44  48
 5 |          25 30 35 40 45  50  55  60
 6 |             36 42 48 54  60  66  72
 7 |                49 56 63  70  77  84
 8 |                   64 72  80  88  96
 9 |                      81  90  99 108
10 |                         100 110 120
11 |                             121 132
12 |                                 144

[edit] XPL0

include c:\cxpl\codes;
int X, Y;
[Format(4, 0);
Text(0, " |"); for X:= 1 to 12 do RlOut(0, float(X));
CrLf(0);
Text(0, " --+"); for X:= 1 to 12 do Text(0, "----");
CrLf(0);
for Y:= 1 to 12 do
[RlOut(0, float(Y)); ChOut(0, ^|);
for X:= 1 to 12 do
if X>=Y then RlOut(0, float(X*Y)) else Text(0, " . .");
CrLf(0);
];
]

Output:

    |   1   2   3   4   5   6   7   8   9  10  11  12
  --+------------------------------------------------
   1|   1   2   3   4   5   6   7   8   9  10  11  12
   2| . .   4   6   8  10  12  14  16  18  20  22  24
   3| . . . .   9  12  15  18  21  24  27  30  33  36
   4| . . . . . .  16  20  24  28  32  36  40  44  48
   5| . . . . . . . .  25  30  35  40  45  50  55  60
   6| . . . . . . . . . .  36  42  48  54  60  66  72
   7| . . . . . . . . . . . .  49  56  63  70  77  84
   8| . . . . . . . . . . . . . .  64  72  80  88  96
   9| . . . . . . . . . . . . . . . .  81  90  99 108
  10| . . . . . . . . . . . . . . . . . . 100 110 120
  11| . . . . . . . . . . . . . . . . . . . . 121 132
  12| . . . . . . . . . . . . . . . . . . . . . . 144
Personal tools
Namespaces

Variants
Actions
Community
Explore
Misc
Toolbox