Show students what code looks like with and without loops to motivate the reasons for using them.

  • Comparing code, like the examples listed below, can help:

    • students understand loops by mapping the code with them back to code without them.

    • motivate loops by helping students see how they make the code easier to understand.

  • Code Comparison Examples:

    • Example code with while loop:

      int count = 0;
      while (count < 6) {
           System.out.println("Count is: " + count);
          count++;
      }

    • Example code with do while loop:

      int count = 0;
      do {
          System.out.println("Count is: " + count);
          count++;
      } while (count < 6);

    • Example code without loop (with iteration):

      int count = 0;
      System.out.println("Count is: " + count);
      count++
      System.out.println("Count is: " + count);
      count++
      System.out.println("Count is: " + count);
      count++
      System.out.println("Count is: " + count);
      count++
      System.out.println("Count is: " + count);
      count++
      System.out.println("Count is: " + count);
      count++

    • Example code without loop:

      System.out.println("Count is: " + 0);
      System.out.println("Count is: " + 1);
      System.out.println("Count is: " + 2);
      System.out.println("Count is: " + 3);
      System.out.println("Count is: " + 4);
      System.out.println("Count is: " + 5);

More about this tip

External Source

Interview with Samar Swaid.