Multiplication tables

Revision as of 17:24, 5 December 2009 by Underscore (talk | contribs) (Added Haskell.)

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

Task
Multiplication tables
You are encouraged to solve this task according to the task description, using any language you may know.

Only print the top half triangle of products.

ALGOL 68

<lang Algol68>main:(

 INT max = 12;
 STRING empty cell = "    ";
 FORMAT fmt = $zz-d$;
 print("   x");
 FOR col TO max DO printf((fmt, col)) OD;
 print (new line);
 FOR row TO max DO
   printf((fmt,row));
   FOR col TO row-1 DO print(empty cell) OD;
   [row:max]INT product;
   FOR col FROM row TO max DO product[col]:=row*col OD;
   printf((fmt, product, $l$))
 OD

)</lang> 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

Haskell

<lang haskell>import Text.Printf

main = do

   putStrLn $ "   x" ++ concatMap fmt [1..12]
   mapM_ putStrLn $ zipWith f [1..12] $ iterate ("    " ++) ""
 where f n s = fmt n ++ s ++ concatMap (fmt . (*n)) [n..12]
       fmt n = printf "%4d" (n :: Int)</lang>

Tcl

<lang 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 ""

}</lang> 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