Definition of a LaTeX for loop

I have turned this code into a package and placed it on CTAN. Rather than copy and paste the code below (which won't be updated), I suggest you download this package and install it.

The following requires the ifthen package.

\newcommand{\forloop}[5][1]% {% \setcounter{#2}{#3}% \ifthenelse{#4}% {% #5% \addtocounter{#2}{#1}% \forloop[#1]{#2}{\value{#2}}{#4}{#5}% }% % Else {% }% }%

which is used in the following manner

\forloop[step]{counter}{initial_value}{conditional}{code_block}

For example:

\newcounter{ct} \forloop{ct}{1}{\value{ct} < 5}% {% \arabic{ct} }

This is the old code that is deprecated

\newcommand{\forLoop}[5][1] {% \setcounter{#4}{#2}% \ifthenelse{ \value{#4} < #3 }% {% #5% \addtocounter{#4}{#1}% \forLoop[#1]{\value{#4}}{#3}{#4}{#5}% }% % Else {% \ifthenelse{\value{#4} = #3}% {% #5% }% % Else {}% }% }

This is invoked by

\newcounter{ct} \forLoop[step]{start}{end}{ct}{latex_code}

The reason for the need to define a counter is to allow nested for loops; for instance, if you wanted to make an 10 by 10 identity matrix:

\newcounter{identRow} \newcounter{identCol} \inp{ \begin{array}{*{10}{c}} \forLoop{1}{10}{identRow} { \forLoop{1}{10}{identCol} { \ifthenelse{ \equal{ \value{identRow} }{ \value{identCol} } }{ 1 }{ 0 } \ifthenelse{ \equal{\value{identCol}}{10} }{}{ & } } \\ } \end{array} }