Skip to content
This repository has been archived by the owner on Oct 9, 2018. It is now read-only.

Conditionals and Looping 1 (Solution)

dimituri edited this page Oct 3, 2010 · 7 revisions

Sample solution

require 'panda_canvas'

PandaCanvas.draw do

  x = 170
  while x < 470
    y = 140
    while y < 340
      pixel x, y
      y += 1
    end
    x += 1
  end

end

Explanation

The approach we use here is called a nested loop.

The first (outer) loop runs once and executes its contents (470 - 170 = 300) times. This way, we move from the leftmost side of our rectangle to the rightmost side.

The second (inner) loop runs as many times as the x varaible changes. Each time the outer loop executes its contents, the inner loop makes (340 - 140 = 200) executions. In this loop the y moves from top to bottom.

This way, pixel x, y runs (300 \times 200 = 60000) times with various values of x and y!

You can nest more than two loops. What you should be wary of is that program speed degrades drastically with each loop you nest.

Move on

Next problem