I’ll show how my triangle pattern sketch works in week4. It looks simple, but it actually uses some important programming ideas like declaring variables, nested for loops, and conditional logic.

At the start of my function, I declare and initialize variables to control the pattern.

For example:


let cols = 10;
let rows = 10;
let triW = width / cols;
let triH = height / rows;


Here, cols and rows decide how many triangles I’ll have. Then I assign values to triW and triH, these calculate each triangle’s width and height based on the canvas size.

So if I change one number, the pattern automatically resizes. This is how variables make code reusable and flexible.

The main logic uses nested for loops, that means one loop inside another. The outer loop goes through each row, and the inner loop goes through each column.

Together, they repeat the same drawing instructions multiple times across the canvas.


for (let r = 0; r < rows; r++) {
  for (let c = 0; c < cols; c++) {
    let x = c * triW;
    let y = r * triH;


Every time the inner loop runs, it updates the position variables x and y to draw a triangle in the right place. So instead of drawing 100 triangles manually, the computer repeats my code 100 times. That’s what makes this logic portable, I can reuse it for any grid pattern.


The next part is this condition:

The modulus operator % gives the remainder when dividing (r+c) by 2. If the result is 0, that means the sum is even, I draw one kind of triangle. If it’s odd, I draw another.


if ((r + c) % 2 == 0) {
  fill(250, 240, 190);
  triangle(x, y + triH, x + triW, y + triH, x + triW / 2, y);
} else {
  fill(200, 210, 225);
  triangle(x, y, x + triW, y, x + triW / 2, y + triH);
}