Tell me more ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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

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

\begin{tabular}{ll}
  \loop\ifnum\theit<4
    \addtocounter{it}{1}
    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?

share|improve this question
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

3 Answers

up vote 7 down vote accepted

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
  \addtocounter{it}{1}
  \expandafter\def\expandafter\mylines\expandafter{%
    \mylines
    Q & A\\
  }%
\repeat

outside the tabular and then

\begin{tabular}{ll}
  \mylines
\end{tabular}
share|improve this answer

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

\documentclass{article}
\newcounter{it}  \setcounter{it}{0}
\newtoks\tabtoks
\newcommand\addtabtoks[1]{\tabtoks\expandafter{\the\tabtoks#1}}
\newcommand*\resettabtoks{\tabtoks{}}
\newcommand*\printtabtoks{\the\tabtoks}
\begin{document}

\resettabtoks
\loop\ifnum\theit<4
  \stepcounter{it} \addtabtoks{Q & A\\}
\repeat

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

\end{document}
share|improve this answer
1  
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|}).

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.