1

I am trying to use the \foreach command to create something with the same effect as:

\begin{align*}
   1 \\
   2
\end{align*}

The following code fails to work:

\begin{align*}
  \foreach \x in {1,2} {
    \x \\
  }
\end{align*}

The error message reads as follows:

! Extra }, or forgotten \endgroup.

I tried to do some research but cannot find anything useful (to me), so any suggestion or advice would be appreciated. Thanks!

Taunch
  • 367
  • 1
    Welcome to TeX-SE! Unfortunately this is not that simple, see https://tex.stackexchange.com/q/439912/121799. –  May 17 '19 at 17:19
  • @marmot Oh, I was not aware of the question that you mentioned. Thanks! – user1161984 May 18 '19 at 05:28

1 Answers1

0

These things are tricky because of expansion issues, see the answers to this question. These answers suggest to load more packages and abandon \foreach. Of course, if you do not insist on \foreach you could just do it without packages and use a recursion to do the loop:

\documentclass{article}
\usepackage{amsmath}
\newcounter{pft}
\def\pftloop{\stepcounter{pft}  \number\value{pft}\\ \ifnum\number\value{pft}<2
\pftloop\fi}
\begin{document}
\begin{align*}
\setcounter{pft}{0}\pftloop
\end{align*}
\end{document}

enter image description here

More complex examples work, too.

\documentclass{article}
\usepackage{amsmath}
\newcounter{pft}
\newcounter{sum}
\def\pftloop{\stepcounter{pft} \setcounter{sum}{\number\value{pft}} 
\number\value{pft}+\stepcounter{pft}\number\value{pft}
\addtocounter{sum}{\number\value{pft}}
&=\number\value{sum}\\ \ifnum\number\value{pft}<9
\pftloop\fi}
\begin{document}
\begin{align*}
\setcounter{pft}{0}\pftloop
\end{align*}
\end{document}

enter image description here

  • Thanks for your explanation. As you guessed, I simply want a loop in an aligned environment, and your method seems to do the trick. – user1161984 May 18 '19 at 05:31