8

I have the following code:

\documentclass[11pt]{article}
\usepackage[a4paper]{geometry}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage{tikz}
\usetikzlibrary{positioning}
\begin{document}
\begin{tikzpicture}[node distance = 0.5cm, auto]
\node (0) {Block 0};
\node (1) [below= of 0.south] {Block 1};
\node (2) [below= of 1.south] {Block 2};
\end{tikzpicture}
\end{document}

It prints this:

enter image description here

I tried to do the same with pgf loop, but don't know how to decrease the counter:

\foreach \x in {0,...,2}
{
  \ifnum\x=0\relax
      \node (\x) {Block \x};
  \else
      %\prev=\x - 1 <- ???
      \node (\x) [below= of \prev.south] {Block \x};
  \fi
}
lockstep
  • 250,273
user4035
  • 5,035
  • 6
  • 40
  • 57

2 Answers2

11

You can use math :)

\foreach \x in {0,...,2}{
  \ifnum\x=0\relax
      \node (\x) {Block \x};
  \else
      \pgfmathparse{int(\x-1)}
      \node (\x) [below= of \pgfmathresult.south] {Block \x};
  \fi
}
percusse
  • 157,807
5

Besides using \pgfmathparse{int(…)} you can also use \pgfmathtruncatemacro or:

  1. eTeX’s \numexpr,
  2. \foreach’s evaluate (again with int),
  3. \foreach’s remember,
  4. \foreach’s count starting from -1 (i.e. first \x minus one)
  5. (recommended) the chains library with start chain=<chain name> going below.

Code

\documentclass[tikz]{standalone}
\usetikzlibrary{positioning,chains}
\tikzset{node distance=.5cm}
\begin{document}
\begin{tikzpicture}
\foreach \x in {0,...,2}{
  \ifnum\x=0\relax
      \node (\x) {Block \x};
  \else
      \node (\x) [below=of \number\numexpr\x-1\relax] {Block \x};
  \fi
}
\end{tikzpicture}

\begin{tikzpicture}
\foreach \x[evaluate=\x as \eval using int(\x-1)] in {0,...,2}{
  \ifnum\x=0\relax
      \node (\x) {Block \x};
  \else
      \node (\x) [below=of \eval] {Block \x};
  \fi
}
\end{tikzpicture}

\begin{tikzpicture}
\foreach \x[remember=\x as \eval] in {0,...,2}{
  \ifnum\x=0\relax
      \node (\x) {Block \x};
  \else
      \node (\x) [below=of \eval] {Block \x};
  \fi
}
\end{tikzpicture}

\begin{tikzpicture}
\foreach \x[count=\eval from -1] in {0,...,2}{
  \ifnum\x=0\relax
      \node (\x) {Block \x};
  \else
      \node (\x) [below=of \eval] {Block \x};
  \fi
}
\end{tikzpicture}

\begin{tikzpicture}[start chain=going below]
\foreach \x in {0,...,2}
  \node[on chain] (\x) {Block \x};
\end{tikzpicture}
\end{document}

Output (all solutions)

enter image description here

Qrrbrbirlbel
  • 119,821