# How to produce multiplication tables/diagram/list using a script

I am a math teacher and would like to produce a LaTeX document that generates multiplication tables. I would like the output to be like

1x5=5

2x5=10

etc.

Can someone help me out?

I can think of two solutions:

1. using pgf's \foreach and \pgfmathparse
2. using LaTeX \@for and counters for arithmetic

# Solution using pgf

With a reasonably recent version of pgf you can write:

\documentclass{article}

\usepackage{pgffor}
\usepackage{pgfmath}

\begin{document}

\foreach \b in {1,...,5}{%
\noindent%
\foreach \a in {1,2,...,10}{%
\pgfmathparse{int(\a*\b)}%
$\a \times \b = {\pgfmathresult}$ \\
}
\newpage
}

\end{document}


which is easily adapted to different styles or functions and highly readable. The two foreach loop through the list in curly brackets, the inner one is the one actually generating the table, the outer is generating the five tables.

The \pgfmathparse macro stores in \pgfmathresult the result of evaluating the expression {int(\a*\b)}. Right after the evaluation of \pgfmathparse the macros \a, \b and \pgfmathresult are setup to hold the first operand, the second and the result of the multiplication respectively.

To make the implementation reusable you can package it into a new macro:

\newcommand{\MultTableOf}[1]{
\foreach \a in {1,2,...,10}{%
\pgfmathparse{int(\a*\b)}%
$\a \times \b = {\pgfmathresult}$ \\
}
}


and then calling it with \MultTableOf{3} for instance.

# Solution using plain LaTeX

If you feel that using pgf is an overkill (it has an incredible lot of more advanced features) or it is not installed in your system, you may consider a pure TeX solution as follows:

\makeatletter
\def\MultTables{1,2,3,4,5}
\def\MultFactors{1,2,3,4,5,6,7,8,9,10}
\newcount\r
\@for\a:=\MultTables\do{
\@for\b:=\MultFactors\do{
\r=\a
\multiply\r by \b
$\a \times \b = \number\r$ \\
}
}
\makeatother


which is a bit less flexible and less readable but requires no extra package. There are two ingredients here: the use of \@for for looping (a more primitive version of pgf's foreach) and the use of counters to perform simple aritmetic.

The virtue of this solution is that it right-justifies numbers to produce a nice alignment.

\documentclass{article}
\usepackage{ifthen}
\newcounter{index}
\newcounter{product}
\usepackage{calc}
\newcount\maxtotal
\newcommand\multt[2]{%
\maxtotal=#1%
\multiply\maxtotal by #2%
\setcounter{index}{0}%
\setcounter{product}{0}%
\whiledo{\theindex<#2}{%
\stepcounter{index}%
\noindent$$\makebox[\widthof{#2}][r]{\theindex}\times #1 =% \makebox[\widthof{\the\maxtotal}][r]{\theproduct}$$\\