Repeating in loops
The easiest calculation is counting, so this will be our starting point. In a for loop, TikZ can count with a variable for us while it repeats a code segment using the variable. While this sounds simple, it’s tremendously valuable for generating graphics with ease, especially with the TikZ \foreach
command, which is incredibly flexible.
The basic syntax of this command is the following:
\foreach variable in {list of values} {commands};
Let’s break down the highlighted code:
variable
: We name and use it like a macro, such as\i
. The convention of using i as a loop variable dates back to the early programming languages and mathematics, when x and y were used for variables and i and j were used as indexing counters. However, we are free to choose any name as long as it starts with a backslash.list of values
: This is a comma-separated list of values, such as1,2,3
. You can omit values and write – for example,1,...,10
–...