7

I'm trying to create a table using the foreach loops made available in the pgffor package. Using the following code, I am able to generate the right contents, but not aligned properly.

\begin{tabular}{c}
    \foreach \i in {0,...,7}{
        \foreach \j in {0,...,7}{
            (\i,\j)
        }
    }
\end{tabular}

However, as soon as I try to add line endings (see below), ..

\begin{tabular}{c}
    \foreach \i in {0,...,7}{
        \foreach \j in {0,...,7}{
            (\i,\j) \\
        }
    }
\end{tabular}

I get the following error:

! Missing \endgroup inserted.
<inserted text> 
                \endgroup 
l.237         }

I don't see what I'm doing wrong. Can anyone point it out to me?

Joost
  • 1,285
  • 2
    cell in tabular is a group http://tex.stackexchange.com/questions/232472/loop-and-char – touhami May 15 '16 at 18:46
  • see also http://tex.stackexchange.com/questions/302323/why-does-a-loop-fail-to-repeat-when-filling-longtable-contents – touhami May 15 '16 at 21:41

1 Answers1

3

Add the contents of the table to a macro before you typeset it:

\documentclass{article}

\usepackage{pgffor,etoolbox}

\newcommand*\mytablecontents{}
\foreach \i in {0,...,7}{
  \foreach \j in {0,...,7}{
    \xappto\mytablecontents{(\i,\j) }
  }
  \gappto\mytablecontents{\\}
}

\begin{document}

\begin{tabular}{c}
  \mytablecontents
\end{tabular}

\end{document}

enter image description here

The code above uses etoolbox's \appto<macro>{<stuff>} which adds <stuff> to the macro <macro>. Or rather it uses its brothers \gappto which adds <stuff> globally (this is important because \foreach performs its loop inside a group) and \xappto which adds <stuff> globally and also expands <stuff> before its added to <macro>. The latter is important because otherwise (\i,\j) would be added multiple times but outside the loop \i and \j have another meaning – you'd get lots of “(ı,ȷ)”.

cgnieder
  • 66,645
  • How can I arrange `\foreach \i in {1,...,6}{ \foreach \j in {1,...,6} \foreach \k in {1,...,6} { \xappto\mytablecontents{(\i,\j,) } – minhthien_2016 Jan 18 '17 at 22:30
  • @toandhsp I don't understand your question. If you replace {0,...,7} with {1,...,6} both times you'll get (1,1) in the uper left corner and (6,6) in the lower right but I guess that's not the question, no? – cgnieder Jan 18 '17 at 22:33
  • @clements My question is \foreach \i in {1,...,6}{ \foreach \j in {1,...,6} \foreach \k in {1,...,6} { \xappto\mytablecontents{(\i,\j,\k) } } – minhthien_2016 Jan 18 '17 at 22:41
  • @toandhsp first you have to decide how you want to arrange the triplets and then you can ask a question of how to achieve the arrangement with LaTeX. Otherwise I'm not sure I can be of any help… – cgnieder Jan 18 '17 at 22:55