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).


2 Answers 2


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:

enter image description here

\usepackage{pgf,pgffor}% http://ctan.org/pkg/{pgf,pgffor}
\foreach \x [count=\xi] in {a_1,a_2,a_3} {%
} \par
\foreach \x [count=\xi] in {1,...,10} {%

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

\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.)

You must log in to answer this question.

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