# For loop print out array contents sequentially

I have already some experience getting \forloop to work in LaTeX but I can't figure out how to get it to print off each item sequentially in a given "array"... Like this pseudo-code would do:

\foreach \n in {a_1,a_2,a_3}{a_i, }


would give:

a_1, a_2, a_3


(notice the lack of a comma after a_3).

-

## migrated from stackoverflow.comFeb 5 '12 at 7:28

This question came from our site for professional and enthusiast programmers.

Here is a way using the count key to store the current index. This allows you to use a different printing style/technique for the first item:

\documentclass{article}
\usepackage{pgf,pgffor}% http://ctan.org/pkg/{pgf,pgffor}
\begin{document}
\foreach \x [count=\xi] in {a_1,a_2,a_3} {%
\ifnum\xi=1
$\x$%
\else
$,\x$%
\fi
} \par
\foreach \x [count=\xi] in {1,...,10} {%
\ifnum\xi=1
$b_1$%
\else
$,b_{\xi}$%
\fi
}
\end{document}

-

This is a programming question, not a TeX question, though since TeX is a programming language, it has a TeX answer. The answer is that you have to be able to tell TeX what the last iteration in the loop is so it can behave differently. One easy (but clunky-looking) way is to write

\foreach \n in {a_1, a_2} {$\n$, }$a_3$


(since this is TeX, I've taken the liberty of putting math-mode around the a_i; not doing this will give an error from the subscript). Another way is to define a "conditional comma", say

\usepackage{etoolbox}
\newcommand\comma[1]{\ifnumgreater{#1}{1}{,}{}}
\foreach \n [count = \c from 1] in {a_1, a_2, a_3} {\comma{\c}$\n$}


which will print a comma after the count \c (recording the number of items printed in the list) passes 1. This avoids the need to update the "last term" code every time you tweak the list. (Obviously better algorithm is taken from Werner's answer.)

Here I've used the etoolbox package, which is quite useful (though overkill for just this one thing) and the facility of \foreach to count iterations in its loop. You should read section 56 of the PGF-2.10 manual, which is short and describes the general behavior of this "function". (There are no actual functions in TeX.)

-