Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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.

share|improve this question
add comment

1 Answer

up vote 4 down vote accepted

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}

enter image description here

share|improve this answer
    
Thank you very much for your nice advice! This works really as I want. –  Andrew Oct 10 '12 at 19:50
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.