# An application of \foreach command in TikZ to generate labels

I would like ask you to help me solve the following application of foreach of TikZ package. By means of the following code:


\documentclass{article}

\usepackage{tikz}

\begin{document}

\begin{tikzpicture}\small
\foreach \x in {0,...,3}
\fill (\x,0) circle (2pt);

\foreach \x in {0,...,3}
\node[above=2pt] at (\x,0) {\x};

\foreach \x in {3.25,3.5,...,4.75}
\fill (\x,0) circle (0.5pt);

\foreach \x in {5,...,8}
\foreach \y in {1,...,4}
{
\fill (\x,0) circle (2pt);
\node[above=2pt] at (\x,0) {$n+\y$};
}

\foreach \x in {8.25,8.5,...,9.75}
\fill (\x,0) circle (0.5pt);
\end{tikzpicture}

\end{document}




I obtain the picture below: where arguments of \y are stacked one upon another. What I aim at are n+1, ..., n+4 labels above the right-hand dots. But I do not know how to tell TikZ to make \y argument dependent on \x in this way. I will be grateful for any hints.

-

## 2 Answers

No need for nested loops, you can use just a simple \foreach and the count= option:

\documentclass{article}

\usepackage{tikz}

\begin{document}

\begin{tikzpicture}\small
\foreach \x in {0,...,3}
\fill (\x,0) circle (2pt);

\foreach \x in {0,...,3}
\node[above=2pt] at (\x,0) {\x};

\foreach \x in {3.25,3.5,...,4.75}
\fill (\x,0) circle (0.5pt);

\foreach \x [count=\xi] in {5,...,8}
{
\fill (\x,0) circle (2pt);
\node[above=2pt] at (\x,0) {$n+\xi$};
}

\foreach \x in {8.25,8.5,...,9.75}
\fill (\x,0) circle (0.5pt);
\end{tikzpicture}

\end{document}


-
Thank you very much. I was not aware of the option and could not find a hint in the TikZ guide. –  Mad Hatter Mar 13 at 21:45

Just for fun, you can reduce the number of foreach loops as follows

% arara: pdflatex
% !arara: indent: {overwrite: yes}
\documentclass{article}
\usepackage{tikz}

\begin{document}

\begin{tikzpicture}
\foreach \x [evaluate={\xi=int(\x-4);}] in {0,...,3,5,6,...,8}
{
\fill (\x,0) circle (2pt);
\ifnum\x<4
\node[above=2pt] at (\x,0) {\x};
\else
\node[above=2pt] at (\x,0) {$n+\xi$};
\fi
}
\foreach \x in {3.25,3.5,...,4.75,8.25,8.5,...,9.75}
\fill (\x,0) circle (0.5pt);
\end{tikzpicture}

\end{document}


This can probably be improved yet further as;

\begin{tikzpicture}
\foreach \x [evaluate={\xi=int(\x-4);}] in {0,...,3,5,6,...,8}
{
\node[fill,circle,inner sep=2pt,label={[above=2pt]90:{\ifnum\x<4\relax\x\else$n+\xi$\fi}}]
(n-\x) at (\x,0) {};
}
\draw[loosely dotted] (n-3) -- (n-5) (n-8) -- ++(2cm,0);
\end{tikzpicture}

-
Very nice example! I am a TikZ beginner so this helps me a lot to improve my understanding of the package. –  Mad Hatter Mar 13 at 22:10
@percusse, I tip my hat to you, sir :) truly marvellous, and extremely gracious of you to make an edit ;) –  cmhughes Mar 13 at 22:31
Nothing compared to your kind words :) –  percusse Mar 13 at 22:34
Could you explain why is 90: put into the code of percusse? With or without it the resulting picture is the same. –  Mad Hatter Mar 23 at 7:38