I don't know why only "for" works while "while" is not working

edited September 2017 in Programming Questions
  1. code by "while" void draw() { x=0; y=0; while(x<width){ x=x+20;

    while(y<height){ y=y+20; star(x,y); }

    }

  2. code by "for"

void draw() { for (x=0; x<width;x= x+20) { for (y=0; y<height;y= y+20) { star(x, y); } } }

variables, x&y were defined already, and star() also was defined based off of variables x and y.

why only the "for" function works here? and what should I do to make the "while" function work as well?

Always thank you for everyone helping me.

Tagged:

Answers

  • edited September 2017 Answer ✓

    https://Forum.Processing.org/two/discussion/15473/readme-how-to-format-code-and-text

    You've gotta reset y iterator variable back to its initial value for the inner while () {} loop before it starts every time! L-)

    for () {} loops automatically reset their iterator back to its initial value before they start. \m/

    // Forum.Processing.org/two/discussion/24017/
    // i-don-t-know-why-only-for-works-while-while-is-not-working#Item_1
    
    // GoToLoop (2017-Sep-04)
    
    final int STEP = 20, DIAM = STEP >> 1, RAD = DIAM >> 1;
    
    smooth(3);
    noLoop();
    noStroke();
    
    colorMode(RGB);
    blendMode(REPLACE);
    rectMode(CORNER);
    
    clear();
    int x = RAD; // initial value
    
    while (x < width) {
      fill((color) random(#000000));
      int y = RAD; // reset to initial value
    
      while (y < height) {
        rect(x, y, DIAM, DIAM);
        y += STEP; // increment by step
      }
    
      x += STEP; // increment by step
    }
    
Sign In or Register to comment.