1. Introduction

In this tutorial, we’ll show how to define loops in a LaTeX document. We’ll cover several methods of doing so.

2. The forloop Package

Let’s look at the forloop command that is part of the forloop package. To use this command, we first need to define a counter variable using the \newcounter{} command. The syntax of this command is as follows:

\forloop{counter}{startValue}{condition}{body}

Here, counter is the loop control variable which is initialized to startValue. The loop’s body is executed as long as condition is true. For instance:

\documentclass{article}
\usepackage{forloop}

\begin{document}
\newcounter{x}
\forloop{x}{1}{\value{x} < 10}{ % value of x is 1...9
    \arabic{x}                  % print x in arabic notation
}
\\                              % print a newline
\end{document}

The output of this program is as follows:

1-d array in Section 2

As we see, the numbers generated by the forloop are printed in a sequence. Afterward, there’s a new line.

2.1. A Nested forloop

We can implement a nested loop as follows:

\forloop{counter1}{startValue1}{condition1}{
   forloop{counter2}{startValue2}{condition2}{
      ...
   }
}

Here’s an example:

\documentclass{article}
\usepackage{forloop}
\setlength{\parindent}{0pt}        % suppress paragraph indent

\begin{document}
\newcounter{x}                     % define two counters
\newcounter{y}
\forloop{y}{0}{\value{y} < 5}{     % y goes from 0 to 4
   \forloop{x}{0}{\value{x} < 10}{ % x goes from 0 to 9
       (\arabic{x},\arabic{y})     % print out tuples
   }
   \\
}
\end{document}

We can see that the output is a grid of tuples:

2d array in section 2.1

The first row is not indented since we set \parindent to zero.

3. The foreach Command

When we wish to explicitly specify the range of the control variable, we can use the foreach command from the pgfor package. The format of this command is:

\foreach \var in {range}{body}

\var is the control variable and we may specify the range as {start…stop}. The loop will be executed for start \leq \var \leq stop.

\documentclass{article}
\usepackage{pgffor}

\begin{document}
\foreach \n in {0,...,10}{
    \n  
}
\\
\end{document}

The output of this code is:

foreach example in section 3

We note that the numbers 0 to 10 inclusive are printed out.

4. The multido Command

We can also use the multido command from the package multido. It allows us to specify the starting value, increment, and the number of values to iterate over:

\multido{\var=start+increment}{numValues}{body}

In this case, our control variable \var can be i (integer), r (real=floating point) or n (number=fixed point). The following code illustrates the use of \multido:

\documentclass[12pt]{article}
\usepackage{multido}
\setlength{\parindent}{0pt}
\thispagestyle{empty}
\begin{document}

Integer, i (positive increment):\\
   \multido{\i=3+4}{10}{\i\ }
   % 10 integer values, start at 3, increment= 4

Integer, i (negative, increment):\\
   \multido{\i=7+-2}{12}{\i\ }
   % 12 integer values, start at 7, increment= -2

Real, r (floating point):\\
   \multido{\r=3.50+0.55}{6}{\r\ }
   % 6 real values, start at 3.50, increment= 0.55

Number, n (fixed point):\\
   \multido{\n=3.50+0.55}{8}{\n\ }
   % 8 fixed point values, start at 3.50, increment= 0.55

\end{document}

Here is the output of the program:

Multido example in Section 4

We notice that for real, i.e., floating-point numbers, there are small variations in the values that are typical of this representation scheme.

5. A Multiplication Table

We’ll now show how to create a 9\times 9 multiplication table using forloops to generate a tabular structure. Basically, that will be a two-dimensional matrix with some additional complications.

For one thing, we need to use a 1-d array to produce the header line (as commented below). Another issue is that we have 11 columns in the table, but the number of tab marks (&s) must be one less.

To take care of the tab marks we use the \ifthenelse command, which has the following format:

\ifthenelse{condition}{action if true}{action if false}

Here is the complete program:

\documentclass{article}
\usepackage{forloop}
\usepackage{calc}    % we need this to be able to multiply (*)

\begin{document}
\newcounter{x}
\newcounter{y}
\newcounter{z}
\begin{tabular}{||r||r|r|r|r|r|r|r|r|r|r||}\hline\hline

\ & %skip the top left cell
\forloop{x}{0}{\value{x} < 10}{ % generates the header row of the table
   \arabic{x} \ifthenelse{\value{x}<9}{&}{}
              % one less '&' than the number of columns
}
\\\hline\hline

\forloop{y}{0}{\value{y} < 10}{

   \arabic{y} \ifthenelse{\value{y}<10}{&}{}

   \forloop{x}{0}{\value{x} < 10}{
       \setcounter{z}{\value{x}*\value{y}}  % '*' needs the calc package
       \arabic{z} \ifthenelse{\value{x}<9}{&}{}
   }   

   \\\hline
}
 &\multicolumn{10}{|c||}{Multiplication Table}\\\hline
\end{tabular}
\end{document}

We thus obtain a neat table:

Multiplication Table in Section 5

An interesting thing is that a doubly nested forloop generates the entries for the standard LaTeX tabular environment.

6. A Two-Dimensional (Grid) Graph

We now present our final and most complex code. We’ll draw a grid graph with directed edges. Here’s the code:

\documentclass{article}
\usepackage[dvipsnames]{xcolor} % needed for non-standard colors
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[myNode/.style={circle,draw,fill=teal,text=white}]

  \foreach \x in {0,...,4}
    \foreach \y in {0,...,4}
       \node [myNode]  (\x\y) at (1.5*\x,1.5*\y) {\x,\y};

  \foreach \x in {0,...,4}
    \foreach \y [count=\yi] in {0,...,3}{
      \draw[-latex] (\x\y)--(\x\yi);
      \draw[-latex] (\y\x)--(\yi\x);
    }   

  \foreach \x [count=\xi] in {0,...,3}
    \foreach \y [count=\yi] in {0,...,3}
      \draw[-latex] (\x\y)--(\xi\yi);

\end{tikzpicture}
\end{document}

The output of this program consists of a 5\times 5 matrix of nodes, colored teal, with coordinates printed in white.

Grid graph in Section 6.1

The directed edges have LaTeX-style arrowheads.

7. Conclusion

In this article, we described several methods of defining loops in LaTeX documents. These allow us to generate complex tables, charts, and graphs.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.