# latex Counters, if statements and loops with latex Loops - repeating things

## Example

We can create loops in latex. They are similar but not as customizable as loops in other programming languages. One alternative to use loops are @loops. If we use a command which includes "@" in its name, we must be put it between \makeatletter and \makeatother. It is not allowed to use them in a macro which describes a new definition.

Wrong:

\def\is#1#2{\makeatletter\@ifstar{#1}{#2}\makeatother


Right:

\makeatletter\def\is#1#2{\@ifstar{#1}{#2}}\makeatother


@for loop: \@for\command:={list}\do{commands}

Example:

\makeatletter
\@for\sun:={rising,setting}\do{The sun is \sun.}
\makeatother


It creates the following text: The sun is rising. The sun is setting.

@whilenum loop: \@whilenum condition\do{commands}

Example:

\makeatletter
\newcounter{int}
\@whilenum\value{int}<10\do
{\stepcounter{int}\ifthenelse{\isodd{\value{int}}}{\theint}{}}
\makeatother


This code writes odd numbers from 1 to 9.

"loop repeat" loop: \loop {commands} \ifnum condition \repeat

Executes commands till condition is true.

Example

\setcounter{int}{1}
\loop
\theint
\ifnum \value{int}<10
\repeat


This code does the same as @whilenum loop.

An example code:

\documentclass{article}
\usepackage{ifthen}
\usepackage{amsmath} %\text{} command needs this package
\begin{document}
Demonstration of @for loop:

\makeatletter
\@for\sun:={rising,setting}\do{The sun is \sun. }
\makeatother

\newcounter{int}

@whilenum loop:

\setcounter{int}{0}
\makeatletter
\@whilenum\value{int}<20\do
{\stepcounter{int}\ifthenelse{\isodd{\value{int}}}{\theint\text{ }}{}}
\makeatother

"loop repeat" loop:

\setcounter{int}{1}
\loop
\theint