Home

for() loops

Diagram showing the order of execution

for loop diagram

Code from class

Squares:

void setup()
{
  size(605, 605);
}

void draw()
{
  for(int y = 5; y <= 505; y = y + 100)
  {
    for(int x = 5; x <= 505; x = x + 100)
    {
      for(int beta = 0; beta <= 40; beta = beta + 10)
      {
        rect(x+beta,y+beta, 95-2*beta, 95-2*beta);
      }
    }
  }
}

Grid lines:

void setup()
{
  size(800, 600);
}

void draw()
{
  background(255);

  // loop horizontally for the vertical lines
  for(int x = 0; x <= width; x = x + 10)
  {
    line(x, height, x, 0);
  }

  // loop vertically for the horizontal lines
  for(int y = 0; y <= height; y = y + 10)
  {
    line(0, y, width, y);
  }

}

Circles:

float tinyangle = 0;
float dist = 0;
int distdelta = 5;

void setup()
{
  size(800, 600);
}

void draw()
{
  background(0);
  for(float angle = 0; angle <= TWO_PI; angle = angle + PI/8)
  {
    fill(random(0, 255), random(0, 255), random(0, 255));
    float x = dist*cos(angle + tinyangle) + width/2;
    float y = dist*sin(angle + tinyangle) + height/2;
    float size = dist/3;
    ellipse(x, y, size, size);
  }
  tinyangle += 0.05;
  dist += distdelta;
  if(dist > 500) {
    distdelta = -5;
  }
  if(dist < 0) {
    distdelta = 5;
  }
}

Other stuff:

float offset = 0.0;

void setup()
{
  size(800, 600);
}

void draw()
{
  background(0);
  for (int radius = 50; radius < 400; radius += 25)
  {
    for (float r = 0; r < 2*PI; r += PI/8)
    {
      float x = cos(r+offset+radius/100.0);
      float y = sin(r+offset+radius/100.0);
      stroke(255-255*radius/400.0);
      strokeWeight(10);
      point(radius*x+width/2, radius*y+height/2);
    }
    offset += 0.00025;
  }
}

Or another version:

float rdelta = 0.0;

void setup()
{
  size(800, 600);
  stroke(255);
  strokeWeight(15);
  colorMode(HSB);
}

void draw()
{
  background(0);
  for (int radius = 1; radius <= 12; radius++)
  {
    stroke(radius/12.0 * 360.0, 100, 100);
    strokeWeight(radius/12.0 * 50.0);
    for (float r = 0; r < 2*PI; r += PI/16)
    {
      if(radius % 2 == 0)
      {
        float x = radius/12.0*500 * cos(r - rdelta + radius/9.0) + width/2;
        float y = radius/12.0*500 * sin(r - rdelta + radius/12.0) + height/2;
        point(x, y);
      }
      else
      {
        float x = radius/12.0*500 * cos(r + rdelta + radius/9.0) + width/2;
        float y = radius/12.0*500 * sin(r + rdelta + radius/12.0) + height/2;
        point(x, y);
      }
    }
  }
  rdelta += 0.005;
}

CSCI 111 material by Joshua Eckroth is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License. Source code for this website available at GitHub.