# Error while trying to compute modulo 3 inside a foreach loop in TikZ

My goal is to draw an array of shapes in the following fashion: square, square, triangle, square, square, triangle ...

I use a \foreach loop in which I use modular arithmetic to determine when to draw a triangle. Here is my MWE:

\documentclass{article}
\usepackage{pgfplots,tikz,tikz-3dplot}
\usetikzlibrary{shapes.geometric}
\begin{document}
\begin{figure}
\centering
\begin{tikzpicture} [scale=0.35,
triangle/.style = {regular polygon, regular polygon sides=3, scale=2.5},
square/.style = {regular polygon, regular polygon sides=4, scale=2}]
\foreach \i in {1,...,9}
{
\ifthenelse{mod(\i,3) = 0}
{
\node[triangle] (\i) at (\i,0) {};
}
{
\node[square] (\i) at (\i,0) {};
}
}
\end{tikzpicture}
\end{figure}
\end{document}


I get the errors:

! Missing number, treated as zero.
! Missing = inserted for \ifnum.


The most related question about these error is this but it considers decimal numbers, which is not my case. What am I missing?

If you look at the log file you'll see the entire error, where you can see it complains about m, so I take it m is what is not a number. Here m is the m in mod.

Point being, \ifthenelse doesn't know about pgfs math functions, and mod isn't parsed in that location. You can do the calculation with \foreach [evaluate={\j=int(mod(\i,3));}] and do the comparison against \j.

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{shapes.geometric}
\begin{document}
\begin{figure}
\centering
\begin{tikzpicture} [scale=0.35,
triangle/.style = {draw, regular polygon, regular polygon sides=3, scale=2.5},
square/.style = {draw, regular polygon, regular polygon sides=4, scale=2}]
\foreach [evaluate={\j=int(mod(\i,3));}] \i in {1,...,9}
{
\ifthenelse{\j = 0}
{
\node[triangle] (\i) at (\i,0) {};
}
{
\node[square] (\i) at (\i,0) {};
}
}
\end{tikzpicture}
\end{figure}
\end{document}

• Thanks for the detailed explanation. This answer is more than I expected! – padawan Sep 19 at 20:32