Having students trace a simple program for drawing a set of squares in Processing to introduce loops and strengthen student understanding for-loops with a body of code through practice.

  • Before jumping into this activity, you’ll want to cover the following topics to introduce for loops.
    • First, explain the conditional for-loop header to students.
      • for (<initialization>, <test>, <increment>)
    • Next, cover ways for-loop conditional statements can be constructed and how to figure out the number of iterations as a class.
      • Students will need practice learning to see how many times they would run.
      • Note from CS Teaching Tips: Checkout out another of Rachel’s Tips that covers this in depth.
  • Activity:
    • Put the following code on the board to introduce for-loops that have a body of code.
      • Note: this code draws 5 squares in Processing from left to right.
int x = 0; int y = 0; int w = 10; int h = 10; for (int i=0; i<5; i++){     rect(x,y,w,h);     x = x+w; }

    • Tell the class you are going to act out the code execution as a class.
    • Go line by line through the code out loud.
      • Every time you come across a variable, assign a student to represent that variable.
      • Have the students representing their variable write down the value of their variable on a personal-sized whiteboard, piece of paper, or class board.
    • When you get to the loop, point out to the class that you need another variable and choose a student to represent the variable i.
      • Make sure this student also write their variable down in the same way the other students did.
    • As you start to trace through the code inside the for-loop, you’ll need to assign two more students:
      • Assign one student to point to what part of the for-loop is being executed on the board.
      • Assign one student to execute the lines being called, this student will draw the pictures on the board when rect is called.
    • After working through body of code once, point out that the variable x is never used outside of the for loop.
      • Students often become interested in the fact that after the loop you can still access x, but can’t access the variable i.
    • After finishing acting through the execution as a class, run the code in Processing so that students can observe the actual code running.
  • Students frequently think that there will be spaces between the squares, use this as teaching opportunity.
    • Talk through what would need to change in the code to space the squares out.
    • Talk through how you might change the height of the boxes.
    • This can be a great time to reinforce that computers do EXACTLY what you tell them to do!
  • As bonus material, you can show students another way to construct this code with more work being done in the conditional statement.
for (int i=0, x=0; i<5; i++, x=x+w){     rect(x,y,w,h); }

More about this tip

External Source

Interview with Rachel Menzies.