# Power of number in loop in TikZ

I need to draw something in TikZ using double loop foreach where in a set in second loop will be the power of number from the first loop. My code isn't work. There is an error when I give 2^{\a} in the second loop. How can I correct it?

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

• Write a separate loop to gain the value of \b=2^{\a} through multiplication. Commented Aug 13, 2016 at 21:45

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}


Using fpeval allthough I am sure there are possibilities with only using tikz and pgf

\documentclass[11pt]{article}
\usepackage{tikz}
\usepackage{expl3}
\ExplSyntaxOn
\cs_set_eq:NN \fpeval \fp_eval:n
\ExplSyntaxOff
\begin{document}
\begin{tikzpicture}

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

• What's \usepackage{fp} for? Commented Aug 13, 2016 at 21:54
• embarrassed. I think I have been mistaken here for a looong time regarding \fpeval. I've now removed the package. Commented Aug 13, 2016 at 21:59