# Need clarification on how this piece of found code is working (recursion)

**URL:** <https://discourse.processing.org/t/need-clarification-on-how-this-piece-of-found-code-is-working-recursion/29969>\
**Category:** Coding Questions\
**Created:** [May 8, 2021, 10:06pm UTC](https://discourse.processing.org/t/need-clarification-on-how-this-piece-of-found-code-is-working-recursion/29969 "2021-05-08T22:06:22Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![Chrisir](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/chrisir/32/45_2.png) [@Chrisir](https://discourse.processing.org/u/Chrisir)\
**Post date:** [May 10, 2021, 8:47am UTC](https://discourse.processing.org/t/need-clarification-on-how-this-piece-of-found-code-is-working-recursion/29969/4 "2021-05-10T08:47:29Z")

</div>

rewritten in processing (and simplified)

```auto
void setup() {
  size(600, 600);
  background(100);
  textAlign(CENTER, CENTER);
  noLoop();
}

void draw() {
  background(100);
  fourRectangles(0, 0, width, 0);
}

//----------------------------------------------------------------------

void fourRectangles(float x, float y, 
  float sizeRect, 
  int depth) {
  // When the depth is still smaller than our random border 
  if (depth < random(0, 8)) {
    // split the rect in four parts and call me again (recursion)
    sizeRect = sizeRect/2; // the new rects have half the size
    int newLevel = depth+1; // the new rects have a depth that's higher than the old by 1 
    // 4 parts / quadrants 
    fourRectangles(x, y, sizeRect, newLevel);// upper left rect (comment one line out to see the missing quadrant)
    fourRectangles(x + sizeRect, y, sizeRect, newLevel); // upper right rect 
    fourRectangles(x + sizeRect, y + sizeRect, sizeRect, newLevel); // lower right rect 
    fourRectangles(x, y + sizeRect, sizeRect, newLevel); // lower left rect
  } else {
    // else: End of recursion: draw ONE rect (using the current local values)
    fill(random(255), random(255), random(255));
    rect(x, y, sizeRect, sizeRect);
    if (depth<=5) {
      fill(0);
      text(depth, x+sizeRect/2, y+sizeRect/2);
    }//if
  }//else
}//func

//-----------------------------------------------------------------------------------------------
// Inputs

void keyPressed() {
  redraw();
}

void mousePressed() {
  redraw();
}
//

```

---

_[View the full topic](https://discourse.processing.org/t/need-clarification-on-how-this-piece-of-found-code-is-working-recursion/29969)._
