The latex kernel has some loops, but with the @
letter, thus their use is not so widespread. The \whiledo
of ifthen
is a wrapper of the \@whilesw
of the latex kernel; the latter is expandable, whereas the \whiledo
wrapper of ifthen
is not. However, here as shown in the answer of the OP's as well as in this answer, one can use with success \whiledo
.
It is possible to recycle the \@whilesw
of LaTeX
and then, there is no problem with the final line in the tabular.
\documentclass[12pt]{article}
% \usepackage{ifthen} % not needed
% \def\tand{&} % not needed
% recycling the \@whilesw of LaTeX into a num test
% pay attention to correctly end explicit numbers in
% \ifnum tests with a space, if they are last.
\makeatletter
\def\xwhilenum #1\do{\@whilesw{\ifnum #1}\fi }
\makeatother
\begin{document}
\newcounter{it}
\begin{tabular}{ll}
\hline
\setcounter{it}{1}%
\xwhilenum{4>\value{it}}\do {%
\stepcounter{it}%
Q & A \\
}%
\hline
\end{tabular}
\makeatother
\par Immediately after the tabular
%
\begin{tabular}{ll}
\hline
before & the loop \\
\setcounter{it}{1}%
\xwhilenum{4>\value{it}}\do {%
\stepcounter{it}%
Q & A \\
}%
still in & the tabular \\
\hline
\end{tabular}
\makeatother
\par Immediately after the tabular
%
\end{document}
\foreach
. See also expansion - Completely expandable loop macro that also works in tabular - TeX - LaTeX Stack Exchange and tables - Extra line in a tabular using expl3 syntax - TeX - LaTeX Stack Exchange