Create a grid of squares (each colored randomly) using a for loop. (Hint: You will need two for loops!) Recode the same pattern using a “while” loop instead of “for.”
// Learning Processing
// Daniel Shiffman
// http://www.learningprocessing.com
// Exercise 6-8: Create a grid of squares (each colored randomly) using a for loop.
// (Hint: You will need two for loops!) Recode the same pattern using a "while" loop instead of "for."
size(200,200);
// With a for loops
for (int x = 0; x < width; x+=10) {
for (int y = 0; y < height; y+=10) {
noStroke();
fill(random(255));
rect(x,y,10,10);
}
}
// With a while loop
/*int x = 0;
while (x < width) {
int y = 0;
while (y < height) {
noStroke();
fill(random(255));
rect(x,y,10,10);
y += 10;
}
x += 10;
}*/









What should I do if i want to use random r,g,b to color them? I was told fill(random(r,g,b)); is not applicable..
Comment by ww — October 2, 2009 @ 1:52 am
You just need to use 3 arguments to fill(), i.e.
Comment by admin — October 6, 2009 @ 10:25 am
I was able to complete first half of ex. 6-8. I cannot figure out how to re-create the same pattern using a “while” loop. This is one of the many attempts I’ve made:
size(200,200);
background(255);
int r = 0;
int g = 0;
int b = 0;
int x = 0;
int y = 0;
while (x<width) {
while(y<height) {
rect(x,y,10,10);
x+=10;
y+=10;
}
println("x = "+x);
println("y = "+y);
}
// r = int(random(255));
// g = int(random(255));
// b = int(random(255));
// fill(r,g,b);
Thanks!
Comment by ps — November 29, 2009 @ 3:00 pm
Here’s how it looks with a while loop. Note the difference regarding where you increment x and y.
int x = 0; while (x < width) { int y = 0; while (y < height) { noStroke(); fill(random(255)); rect(x,y,10,10); y += 10; } x += 10; }Comment by Daniel Shiffman — November 29, 2009 @ 7:01 pm
Thank you!
Comment by ps — November 30, 2009 @ 6:57 pm