5

I want to print the numbers 0,1,...,n-1 in a tabular environment. My first attempt resulted in the error Incomplete \iffalse; all text was ignored after line 19.. By "hiding" & (ampersand) in a construct solves the problem. But this looks ugly. Is there a nice way to be able to use \whiledo{}{} programming in a tabular?

Here is my code:

\documentclass{article}
\usepackage{ifthen,calc}
\newcounter{x}
\newcommand{\ampersand}{\ifthenelse{0<1}{&}{}}
\newcommand{\numbers}[1]{\begin{tabular}{|c@{x=}|*{#1}{r|}}
\hline\setcounter{x}{0}
%
% my first attempt produces error:
%
\whiledo{\thex<#1}{&\thex\stepcounter{x}}\\
%
% no error if above line is replaced with:
%
% \whiledo{\thex<#1}{\ampersand\thex\stepcounter{x}}\\
%
\hline\end{tabular}}
\begin{document}\numbers{10}\end{document}

1 Answer 1

5

When TeX sees &, it ends the current alignment cell; but you cannot start a \whiledo process in one cell and end it in a different one. With \def\ampersand{&} you're delaying the interpretation to when macro expansion takes place; but you're being lucky, actually.

I wouldn't use \whiledo; there are more powerful tools, nowadays.

\documentclass{article}

\ExplSyntaxOn

\NewDocumentCommand{\numbers}{O{0}m}
 {
  \ensuremath
   {
    \begin{array}
     {
      |c|
      *{ \int_eval:n { #2 + 1 - #1 } }{r|}
     }
    \hline
    x=
    \int_step_function:nnN { #1 } { #2 } \battha_print_number:n \\
    \hline
    \end{array}
   }
 }

\cs_new:Nn \battha_print_number:n { & #1 }

\ExplSyntaxOff

\begin{document}

\numbers{9}

\medskip

\numbers[1]{9}

\medskip

\numbers[2]{10}

\end{document}

enter image description here

TeX will take care of the arithmetic, so you just specify the end point and, optionally, the start point (default is 0).

A possible improvement is to make the cells to have equal width if the end number is two-digit.

\documentclass{article}
\usepackage{array}

\ExplSyntaxOn

\NewDocumentCommand{\numbers}{O{0}m}
 {
  \ensuremath
   {
    \int_compare:nTF { #2 > 9 }
     {
      \newcolumntype{B}{w{r}{1em}}
     }
     {
      \newcolumntype{B}{w{r}{0.5em}}
     }
    \begin{array}
     {
      |c|
      *{ \int_eval:n { #2 + 1 - #1 } }{B|}
     }
    \hline
    x=
    \int_step_function:nnN { #1 } { #2 } \battha_print_number:n \\
    \hline
    \end{array}
   }
 }

\cs_new:Nn \battha_print_number:n { & #1 }

\ExplSyntaxOff

\begin{document}

\numbers{9}

\medskip

\numbers[1]{9}

\medskip

\numbers[2]{10}

\end{document}

enter image description here

The column type B is locally defined to be w{r}{0.5em} if the final number is one-digit; 1em otherwise.

1
  • This makes it clear to me what happens in TeX's "stomach". Thanks! Aug 10, 2022 at 18:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .