Encourage students to replace variables with values when tracing through code to reduce the necessary cognitive load.

Like(2034 Likes)
  • The fewer variables students have to keep track of when tracing through code, the easier it will be.
  • Substituting various values for a variable can also demonstrate a pattern.
  • Examples:
    • Java code from the 2009 AP CS A exam multiple choice, what value is returned as a result of the call sol(10)?
      public int sol(int lim) { 
      • int s = 0;
      • for (int outer = 1; outer <= lim; outer++) {  
        • for (int inner = outer; inner <= lim; inner++) { 
          • s++;
        • }
      • }
        • return s;
    • }
      • In the Java code above, students can cross out lim and write in 10 to make tracing through this code easier. Each time they trace through the inner loop, students can cross out outer and replace it with the current value of outer.
        • This way students don’t have to keep track of the values of lim, outer, inner, and s in their head at the same time. When tracing through the inner loop, they can focus on the values of inner and s.
    • Java code from 2009 AP CS A exam multiple choice: How many times is "Hello!" printed, where k is a random number such that 1 ≤ k ≤ n.
      • for (int p=2; p<=k; p++) {
        • for (int r=1; r<k; r++) {
          • System.out.println("Hello!");
        • }
      • }
        • In the Java code above, encourage students to cross out variables and fill with exact values before tracing through the loop to avoid confusion and reduce the number of things they need to hold in their working memory.
        • Don’t substitute 1 or 2 for variables since these values can lead to additional misconceptions.
          • If we substitute n=2 in the code above, it would execute the same number of times as two sequential for loops with the same bounds since 2+2=2*2.

More about this tip

External Source

Leigh Ann Sudol-DeLyser’s notes from 2009 AP CS A exam.