# How to make tabularx columns using \whiledo?

My question is similar to that discussed in How to programmatically make tabular rows using \whiledo ?. The difference is that I want to produce columns rather than rows with using \whiledo. Basically I have the code:

\documentclass{article}
\usepackage{tabularx}

\newcounter{index}
\setcounter{index}{3}
\newcommand{\Line}{& 1 & 2 & 3}

\begin{document}
\begin{tabularx}{0.9\textwidth}{|r|*{\value{index}}{X|}}
\hline
Some text \Line \\
\hline
\end{tabularx}
\end{document}

My task is to redefine the command \Line such that it would have one argument, value of the counter index. It should produce columns with the content 1, 2, 3, ..., n. Here n is value of the counter index.

I am filling that there exists a solution with \whiledo but still my attempts to find it are unsuccessful. I would be appreciate for any help.

My advice is to never use \whiledo or other loops inside a tabular environment or variations thereof.

The strategy is to build the \Line macro step by step; producing a & in a tabular environment would end a cell and break the loop. Better do it when you set the value of index for the next job.

\newcounter{index}
\newcounter{temp}
\newcommand{\settabindex}[1]{%
\setcounter{index}{#1}%
\setcounter{temp}{0}%
\def\Line{}%
\whiledo{\value{temp}<\value{index}}
{\stepcounter{temp}\edef\Line{\Line & \thetemp}}%
}

One needs to use \edef in order to deliver the previous contents of \Line for the next addition of & \thetemp.

Example:

\documentclass{article}
\usepackage{tabularx,ifthen}

\newcounter{index}
\newcounter{temp}
\newcommand{\settabindex}[1]{%
\setcounter{index}{#1}%
\setcounter{temp}{0}%
\def\Line{}%
\whiledo{\value{temp}<\value{index}}
{\stepcounter{temp}\edef\Line{\Line & \thetemp}}%
}

\begin{document}

\settabindex{10}
\begin{tabularx}{0.9\textwidth}{|r|*{\value{index}}{X|}}
\hline
Some text \Line \\
\hline
\end{tabularx}

\settabindex{4}

\begin{tabularx}{0.9\textwidth}{|r|*{\value{index}}{X|}}
\hline
Some text \Line \\
\hline
\end{tabularx}

\end{document}

• Thank you very much for your nice advice! This works really as I want. – Andrew Oct 10 '12 at 19:50