Show a variety of for loops conditionals (e.g., < vs. <=; different variable names, different start values, different increment operations) to avoid common misconceptions about loops.

  • Exercise: Provide students multiple for-loop counters that loop 10 times in different ways and ask them how many of these will loop 10 times.
  • When you say less than 10, students think that there are less than 10 steps. This results from a struggle with indexing starting from 0.
        for (int i = 0; i < 10; i++)
  • Show students an example where the index doesn’t just increase by 1.
        for (int i = 0; i < 20; i=i+2)
        for (int i = 0; i < 20; i--)
  • Show students examples using <= to compare it to just using =.
        for (int i = 0; i <= 9; i++)
  • Students often expect that the index of a for loop has to start at 0:
        for (int i = 5; i < 15; i++)
  • Students sometimes assume that for loops must use variables named i or j.
        for (int count = 5; k < 15; count++)
  • Help students see the connection between for loops and arrays with indexes starting at 0.
    • If you want 10 things when i=0 you need to loop up to <10.
      • If you want to place these items into an array, students then conclude that there are 10 items but less than 10 place containers in the array for these 10 items.
      • Explicitly map for students that the 10th item belongs at array index 9, the 9th item belongs at array index 8, all the way down to the 1st item belongs at array index 0.

More about this tip

External Source

Interview with Rachel Menzies.