problem with using loop inside the tabular environment

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}

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}

Your own answer has to deal with the extra line problem. Here is a way to do that without having to separately construct the last line thereby keeping your table line structure in one place inside the loop. I threw in a \hline or two to show they don't upset the applecart either.

Solution Output

\documentclass[12pt]{article}
\usepackage[a6paper,landscape]{geometry}

\usepackage{ifthen}

\def\tand{&}

\begin{document}
%
\newcounter{it}
\begin{tabular}{ll}
\hline
  \setcounter{it}{1}%
  \whiledo{\theit<4}{%
    Q \tand A \\%
    \ifnum\value{it}=3\hline\end{tabular}\fi
  \stepcounter{it}%
  }%
 \par Immediately after the table
%
\end{document}

Tags:

Loops

Tables