# Iterative nested drawing in TikZ

I want to draw an iterative coloured square, so that a square gets divided into four subsquares and the top right subsquare is coloured and for the three remaining subsquares repeat this procedure. I'd like to use TikZ to accomplish this, but I don't want to draw everything "by hand".

I already found out about the nested pics and about l-systems but I'm not able to get them into proper code, especially because I don't understand the theory of l-systems.

I am sure I could do it with some nested foreach and nested pics, always scaled to fit, but if there is another simpler method I'd be happy - four or five iterations would be nice.

Here is an example of what the first iteration looks like:

## 2 Answers

You can do this with l-system but a classic macro is ok too. Here is one way to do it.

\documentclass[tikz,border=7pt]{standalone}
% #1 is a countdown parameter
\newcommand{\fillsquare}[1]{
% last step is 1, after that do nothing
\ifnum #1 > 0\relax
% fill and draw
\fill[orange] (0,0) rectangle (1,1);
\draw  (-1,-1) grid (1,1);
% recursive call to \fillsquare after scale and translate
\begin{scope}[scale=.5]
\foreach \p in {(-1,1),(-1,-1),(1,-1)}{
\begin{scope}[shift={(\p)}]
\fillsquare{\numexpr #1-1}
\end{scope}
}
\end{scope}
\fi
}
\begin{document}
\begin{tikzpicture}
\fillsquare{4}
\end{tikzpicture}
\end{document}


I was able to go up to 7 levels on my system.

  \begin{tikzpicture}[line width=0.05pt]
\fillsquare{7}
\end{tikzpicture}


May I suggest to let the user choose the length of the original square by adding another parameter?

Please don't accept my answer as it is only a tiny upgrade of what Kpym did very well above.
He deserves all the love^^.

\documentclass[tikz,border=7pt]{standalone}
% #1 is a countdown parameter
\newcommand{\fillsquare}[2]{
% last step is 1, after that do nothing
\ifnum #1 > 0\relax
% fill and draw
\fill[orange] (0,0) rectangle (#2,#2);
\draw  (-#2,-#2) grid[step=#2] (#2,#2);
% recursive call to \fillsquare after scale and translate
\begin{scope}[scale=.5]
\foreach \p in {(-#2,#2),(-#2,-#2),(#2,-#2)}{
\begin{scope}[shift={(\p)}]
\fillsquare{\numexpr #1-1}{#2}
\end{scope}
}
\end{scope}
\fi
}
\begin{document}
\begin{tikzpicture}[line width=0.05pt]
% First parameter is the number of steps
% Second parameter is the length of the initial square
\fillsquare{6}{4}
\end{tikzpicture}
\end{document}