1

Are there any simple way to perform repetition inside a tabular environment?

This is what I intended to do:

\documentclass[a4paper,10pt]{scrartcl}

\usepackage[utf8]{inputenc}
\usepackage{tikz}
\usepackage{ifthen}


\newcommand\encircle[1]{%
  \tikz[baseline=(X.base)] 
    \node (X) [draw, shape=circle, inner sep=0] {\strut #1};}

\begin{document}

\renewcommand{\arraystretch}{1.25}

\pagestyle{empty}

\begin{tabular}{|c|c|c|c|c|c|}
  \hline
  \newcounter{qno}
  \setcounter{qno}{1}
  \whiledo{\value{qno} < 41}{
  \theqno.
  & \encircle{a}
  & \encircle{b}
  & \encircle{c}
  & \encircle{d}
  & \encircle{e}
  \\
  \hline
  \stepcounter{qno}  
  }
\end{tabular}


\end{document}

But it produces an compilation error, a blank page, and a table with three extra lines at the end.

I am aware of a possible solution, but I was wondering if there is any solution that do no require redefining things.

Bernard
  • 271,350
Jeff
  • 251
  • Any solution will use a strategy similar to the one used in the post that you quoted. This is due to the special way used by tabular(x)(*) to handle his content. It should be fully available at the whole when TeX start to parsing it, which not the case if the loop is inside the tabular. – Jhor Jun 24 '18 at 17:55

1 Answers1

2

It's easy with expl3, because \int_step_function:nnnN delivers its result before TeX restarts to examine the output.

\documentclass[a4paper,10pt]{scrartcl}

\usepackage{tikz}
\usepackage{xparse}

\newcommand\encircle[1]{%
  \begin{tikzpicture}[baseline=(X.base)]
  \node (X) [draw, shape=circle, inner sep=0] {\strut #1};
  \end{tikzpicture}%
}

\ExplSyntaxOn
\NewDocumentCommand{\maketabularlines}{mm}
 {
  \int_step_function:nnnN { 1 } { 1 } { #1 } #2
 }
\ExplSyntaxOff
\NewDocumentCommand{\abcdeline}{m}{%
  #1. 
  & \encircle{a}
  & \encircle{b}
  & \encircle{c}
  & \encircle{d}
  & \encircle{e}
  \\
  \hline
 }

\begin{document}

\renewcommand{\arraystretch}{1.25}

\begin{tabular}{|c|c|c|c|c|c|}
\hline
\maketabularlines{10}{\abcdeline}
\end{tabular}

\end{document}

You can use different macros in place of \abcdeline so long as the argument to the macro is the current index in the loop.

enter image description here

egreg
  • 1,121,712