# Change Tikz style dependent on foreach counter value

I have a recursive macro that relies on a counter within a tikz \foreach loop. What I have not achieved is how to get a tikz style (what I've called fillMod) to be dependent on the counter value (i.e. depending on whether \n is odd or even). Below is a MWE of what I so far have.

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning}

\begin{document}

\newcommand{\pic}[1]{%
\begin{tikzpicture}[scale=3,
fillEven/.style={fill=red},
fillOdd/.style= {fill=blue},
fillMod/.style= {}]

\coordinate (A0) at (0,0);

\foreach \n in {1,2,...,#1}
{
\draw[fillMod,scale={pow(0.8,\n)}] (A0)--++(1,0)node(D0){}--++(0,-1)--++(-1,0)--++(0,1);

\coordinate (A0) at (D0);
\coordinate[below=30mm of A0]   (D0);
}
\end{tikzpicture}
}

\pic{2}

\pic{3}

\pic{4}

\pic{5}

\end{document}


I know that I can define within the loop two \draw paths, one for red and one for blue, but that means I can only produce pictures with an even number of squares. Is there a way to do this?

Something like this perhaps.

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning}
\newcommand{\pic}[1]{%
\begin{tikzpicture}[scale=3]

\coordinate (A0) at (0,0);

\foreach \n in {1,2,...,#1}
{
\ifodd\n
\tikzset{fillMod/.style={fill=blue}}
\else
\tikzset{fillMod/.style={fill=red}}
\fi
\draw[fillMod,scale={pow(0.8,\n)}] (A0)--++(1,0)node(D0){}--++(0,-1)--++(-1,0)--++(0,1);

\coordinate (A0) at (D0);
\coordinate[below=30mm of A0]   (D0);
}
\end{tikzpicture}
}

\begin{document}
\pic{2}

\pic{3}

\pic{4}

\pic{5}

\end{document}


• Yes, as you say, something like this!! Many thanks. – Geoff Mar 21 '16 at 19:08

Here is as solution without explicit test. The second example shows an example with four styles.

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning}

\begin{document}

\newcommand{\pic}[1]{%
\begin{tikzpicture}[scale=3]
\tikzset{
fill 0/.style={fill=red},
fill 1/.style= {fill=blue},
}

\coordinate (A0) at (0,0);

\foreach \n [evaluate=\n as \snum using {int(mod(\n,2))}] in {1,2,...,#1} {
\draw[fill \snum,scale={pow(0.8,\n)}]
(A0)--++(1,0)node(D0){}--++(0,-1)--++(-1,0)--++(0,1);
\coordinate (A0) at (D0);
\coordinate[below=30mm of A0]   (D0);
}
\end{tikzpicture}
}

\pic{2}

\pic{3}

\pic{4}

\pic{5}

\end{document}


Example with four styles:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning}

\newcommand{\pic}[1]{%
\begin{tikzpicture}[scale=3]
\tikzset{
fill 0/.style={fill=red},
fill 1/.style= {fill=blue},
fill 2/.style= {fill=green},
fill 3/.style= {fill=orange},
}
\coordinate (A0) at (0,0);
\foreach \n [evaluate=\n as \snum using {int(mod(\n,4))}] in {1,2,...,#1} {
\draw[fill \snum,scale={pow(0.8,\n)}]
(A0)--++(1,0)node(D0){}--++(0,-1)--++(-1,0)--++(0,1);
\coordinate (A0) at (D0);
\coordinate[below=30mm of A0]   (D0);
}
\end{tikzpicture}
}

\begin{document}
\pic{2}\par
\pic{3}\par
\pic{4}\par
\pic{5}\par
\end{document}