Apr 22

# A For loop in LaTeX!

Here is some beautiful code I found on the internet some time ago, which produces a recursive for loop in LaTeX:

%%% FOR LOOP CODE
\usepackage{ifthen}
\newcommand{\forLoop}[5][1]{%
\setcounter{#4}{#2} %
\ifthenelse{ \value{#4}&lt;#3 }%
{%
#5 %
\forLoop[#1]{\value{#4}}{#3}{#4}{#5} %
}%
{%
#5 %
}%
}%
%% END FOR LOOP CODE


The syntax is:

\forLoop[STEP]{START}{END}{COUNTERNAME}{COMMANDS}

This code will execute COMMANDS inside a for loop that starts at START, goes up by STEP, and ends at END. COUNTERNAME is the counter used to maintain the index of the loop. As usual, the best way to show this is using a sample document, so here it is! There are 3 examples: one simple sentences, a second in math mode, and a third complicated example that calculates the Fibonacci numbers!! Enjoy!!

\documentclass{article}

\usepackage{calc} %% Just need this to be able to divide values in example 3

%%% FOR LOOP CODE
\usepackage{ifthen}
\newcommand{\forLoop}[5][1]{%
\setcounter{#4}{#2} %
\ifthenelse{ \value{#4}&lt;#3 }%
{%
#5 %
\forLoop[#1]{\value{#4}}{#3}{#4}{#5} %
}%
{%
#5 %
}%
}%
%% END FOR LOOP CODE

\begin{document}

\newcounter{index}

\section{Example 1}

\forLoop[2]{6}{12}{index}
{
This is inside the for loop: iteration \theindex\\
}

\section{Example 2}

$$\forLoop{1}{20}{index} { x^{\theindex} }$$

\section{Example 3}

\newcounter{fibold1}%
\newcounter{fibold2}%
\setcounter{fibold1}{1}%
\setcounter{fibold2}{1}%
\newcounter{fibcurr}%
\newcounter{tempcounter}%

\begin{eqnarray*}
&amp; 1, 1, \forLoop{1}{40}{index} {
\setcounter{fibcurr}{0}
\thefibcurr,
\setcounter{tempcounter}{\value{index}-(\value{index}/5)*(5)}
\ifthenelse{ \value{tempcounter} = 0 }
{
\\
&amp;
}
{
}
\setcounter{fibold1}{\value{fibold2}}
\setcounter{fibold2}{\value{fibcurr}}
}
\end{eqnarray*}

\end{document}


Enjoy and Keep Learning! -Rob