# problem with using loop inside the tabular environment

I am having trouble with using a loop inside a tabular environment:

\newcounter{it}
\setcounter{it}{0}

\begin{tabular}{ll}
\loop\ifnum\theit<4
Q & A\\
\repeat
\end{tabular}


I receive an error about argument of loop having an extra } and the compilation stops at &. I don't get an error when it is a single column table, but even in that case the result is not as expected: I get a single execution of the loop in place of 4.

Can someone tell me what I am missing? Is there special considerations when using loops inside tabular?

-
 I found out that to solve the problem with & I can define something like \def\tand{&} and use \tand in place of &. But I still get an incorrect output. – Kaveh Apr 1 '12 at 7:05

Yep, don't do that. tabulars are really special and macro-unfriendly (for instance every & closes a group).

Try

\def\mylines{}%
\loop\ifnum\theit<4
\expandafter\def\expandafter\mylines\expandafter{%
\mylines
Q & A\\
}%
\repeat


outside the tabular and then

\begin{tabular}{ll}
\mylines
\end{tabular}

-

collect all lines with a token register and then print the lines:

\documentclass{article}
\newcounter{it}  \setcounter{it}{0}
\newtoks\tabtoks
\newcommand*\resettabtoks{\tabtoks{}}
\newcommand*\printtabtoks{\the\tabtoks}
\begin{document}

\resettabtoks
\loop\ifnum\theit<4
\repeat

\begin{tabular}{ll}
\printtabtoks
\end{tabular}

\end{document}

-
This technique has been introduced here by you as well. – Click Me Apr 1 '12 at 7:09

I solved my problem by using a while loop instead:

\def\tand{&}

\newcounter{it}
\begin{tabular}{ll}%
\setcounter{it}{1}%
\whiledo{\theit<3}{%
Q \tand A \\%
\stepcounter{it}%
}%
{\theit} \tand \\
\end{tabular}


PS: if wondering why I need to print the last one separately, the reason is that the execution leave a partial line (I am using tabular{|l|l|}).

-