Power of number in loop in TikZ

Just do the math before the inner loop. foreach doesn't parse math in the iterable list

\begin{tikzpicture}
\foreach \a in {1,2,3}
{
    \pgfmathtruncatemacro\aa{2^\a}
    \foreach \b in {1,2,...,\aa}
    {
    \draw (0,\a)--(\b,0);
    }
}
\end{tikzpicture}

or use the evaluate key.


You may use the evaluate option of \foreach loop:

\begin{tikzpicture}
\foreach \a[evaluate=\a as \bmax using int(2^\a)] in {1,2,3}
{
    \foreach \b in {1,2,...,\bmax}
    {
    \draw (0,\a)--(\b,0);
    }
}
\end{tikzpicture}

An alternative loop with expl3; the current integer in the outer loop is designed as #1 (your \a), the current one in the inner loop is designed as ##1 (your \b).

\documentclass{article}
\usepackage{tikz,xparse}

\ExplSyntaxOn
\DeclareExpandableDocumentCommand{\Xint}{m}
 {
  \fp_to_int:n { #1 }
 }
\NewDocumentCommand{\Xforeach}{mmmm}
 { % #1 = start, #2 = step, #3 = end
  \int_step_inline:nnnn { #1 } { #2 } { #3 } { #4 }
 }
\ExplSyntaxOff

\begin{document}

\begin{tikzpicture}
\Xforeach{1}{1}{3}{
  \Xforeach{1}{1}{\Xint{2^#1}}{
    \draw (0,#1) -- (##1,0);
  }
}
\end{tikzpicture}

\end{document}

enter image description here

Tags:

Loops

Tikz Pgf