# simple arithmetic on index of foreach statement in tikz

Is foreach really a tikz statement or is derived from some other package?

I would like to draw a horizontal axis with 7 ticks spaced 1 cm apart. I'd like to place a label under each tick that is the ordinal number of the tick (1,2,3..) and a label above the tick that is the value of the ordinal number multiplied by the constant 3.14

-

Two solutions using only foreach own computing tools

\foreach \x [count=\i] in {3.14,6.28,...,21.98}


Difference between second and first items in list is calculate and added to second and successive values until it reaches the last one. On the same time \i counts list items.

\foreach \i [evaluate=\i as \x using \i*3.14] in {1,2,...,7}


\i advances through the list and it's used to calculate a new variable \x.

Both solutions produce the same result:

The complete code could be:

\documentclass{article}
\usepackage{tikz}
\begin{document}

\begin{tikzpicture}

\foreach \x [count=\i] in {3.14,6.28,...,21.98} {
\draw (\i,-4pt) -- (\i,4pt)
node [below,yshift=-2ex] {\i}
node [above] {\x};
}

\draw [-latex] (1,0) -- (7.6,0);

\end{tikzpicture}

\begin{tikzpicture}

\foreach \i [evaluate=\i as \x using \i*3.14] in {1,2,...,7} {
\draw (\i,-4pt) -- (\i,4pt)
node [below,yshift=-2ex] {\i}
node [above] {\x};
}

\draw [-latex] (1,0) -- (7.6,0);

\end{tikzpicture}
\end{document}

-

Yes, foreach is a TikZ/PGF statement. It is described in the very detailed pgfmanual. You can also use it independently of TikZ/PGF by issuing \usepackage{pgffor} in your preamble. This is not necessary if you're using TikZ, as it will be loaded automatically.

Here's an example of how to achieve what you described in your question. \pgfmathsetmacro<macroname>{<expression>} uses the PGF math engine to do the calculation and assigns the result to a macro, while \pgfmathprintnumber rounds and outputs the result.

\documentclass{article}
\usepackage{tikz}
\begin{document}

\begin{tikzpicture}

\foreach \x in {1,...,7} {
\pgfmathsetmacro\result{\x * pi}
\draw (\x,-4pt) -- (\x,4pt)
node [below,yshift=-2ex] {\x}
node [above] {\pgfmathprintnumber{\result}};
}

\draw [-latex] (1,0) -- (7.6,0);

\end{tikzpicture}
\end{document}


-
thanks, Jake. Is there an implicit loop index in foreach that can be referenced by the user? – user5504 May 13 '11 at 17:50
You can use /pgf/foreach/count for that. Write something like \foreach \x [count=\i] in {a,...,z} and \i will hold the loop counter (e.g. 1 for a, 2 for b etc.). – Jannis Pohlmann May 13 '11 at 23:18