A for loop repeats a code block under init, test, and update, turning one drawing procedure into a whole pattern
The for loop is the primary iteration tool in Processing and p5.js, inheriting Java-style syntax with three parts in the parentheses: an init that declares and assigns the counter before the first iteration (int h = 10 or let i = 0), a test — a boolean expression evaluated before each iteration, with the loop exiting when it becomes false (h <= height, i < n) — and an update run after each iteration, typically incrementing or decrementing (h += 10, i++). Because the test is checked before each pass, a loop whose test starts false runs its body zero times. The counter lets each iteration act on a different value — computing positions, sizes, colors, or indexing into an array — so a single shape-drawing procedure becomes a field, grid, or pattern, and the number of repetitions becomes one editable value instead of copy-pasted statements. Nested for loops are the standard pattern for 2D grids. A while loop expresses the same repetition when the count is not known in advance.
Examples
for (int i = 0; i < 10; i++) {
circle(i * 40 + 20, 200, 30); // ten circles in a row, no repeated code
}
Map the counter to a property for a gradient of lines: for (int h = 10; h <= height; h += 10) { stroke(0, 255 - map(h,0,height,0,255)); line(10, h, width-20, h); } — opacity fades across the field. A while loop can draw concentric ellipses for shrinking diameters until a threshold.
Assessment
Rewrite five near-identical circle() calls as a single for loop and state how many times the body runs for for (let i = 0; i < 4; i++). Trace for(int x=0; x<3; x++){ println(x); }, list the values printed, then modify it to count backward from 10 to 0 in steps of 2. Explain what map() does inside a counter-driven stroke() and how you would rewrite a loop drawing horizontal lines to draw vertical ones instead.