home/ atoms/ processing-for-loop

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.

“for (int h = 10; h <=height; h+=10) { stroke(0, 255-map(h,0,height,0,255)); line(10, h, width-20, h);”
corpus · generative-art-code-examples-josephfiola-genart-processing-p · chunk 19
“int tempdiam=diam; while (tempdiam > 10) { strokeWeight(strokeThickness/4); ellipse(centX, centY, tempdiam, tempdiam); tempdiam-=11;”
corpus · generative-art-code-examples-josephfiola-genart-processing-p · chunk 15
“if (diam >= width-width/4) { grow = false; } if (diam <= 0) { grow = true; }”
corpus · generative-art-code-examples-josephfiola-genart-processing-p · chunk 16
“A for loop can execute a section (or block) of code multiple times.”
“The parenthesis associated with the structure enclose three statements: init, test, and update.”
corpus · processing-handbook-no-login-mirror-pdf-reas-and-fry · chunk 21