- When students are provided code, it is crucial they understand the loop bounds when indexing through an array so they can write proper loop bounds themselves.
- The Java code below demonstrates both forwards and backwards looping.
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
//forwards:
for (int i=0; i<arr.length; i++) {- System.out.println(arr[i]);
}
//backwards:
for (int i=arr.length-1; i>=0; i--) {- System.out.println(arr[i]);
}
- More complex looping, like in the Java code below that prints every other element of an array, can further students’ understanding of array looping.
for (int i=0; i<arr.length/2; i=i+2) {
- System.out.println(arr[i]);
}