«

»

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}<#3 }%
   {%
      #5 %
      \addtocounter{#4}{#1} %
      \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}<#3 }%
   {%
      #5 %
      \addtocounter{#4}{#1} %
      \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*}
& 1, 1, \forLoop{1}{40}{index} {
   \setcounter{fibcurr}{0}
   \addtocounter{fibcurr}{\value{fibold1}}
   \addtocounter{fibcurr}{\value{fibold2}}
   \thefibcurr,
   \setcounter{tempcounter}{\value{index}-(\value{index}/5)*(5)}
   \ifthenelse{ \value{tempcounter} = 0 }
   {
      \\
      &
   }
   {
   }
   \setcounter{fibold1}{\value{fibold2}}
   \setcounter{fibold2}{\value{fibcurr}}
}
\end{eqnarray*}

\end{document}

Enjoy and Keep Learning! -Rob

2 comments

  1. Simone

    This code does not work at all.

    1. admin

      I’m happy to help with any problems you’re having. It works for me. Can you be more specific what’s wrong?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

What is 11 + 2 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)