4.2 For Loops

Similar to while loops, for loops run until a condition is false. Format of for loop below:

for (int i = 0; i < 5; i++) {
    System.out.println(i);
}
0
1
2
3
4

Explanation

  • in the above for loop:
    • int i = 0 defines the iterating variable
    • i < 5 is the condition (once i < 5 is false, this loop breaks)
    • i++ is the incrementation of the iterating variable
    • System.out.println(i); is the body code that runs every time the loop iterates

For Each Loops:

  • Apart from iterating using an incrementing variable, you can also iterate through items in a list.

    Example of For Each loop below

int[] list = {1, 2, 3, 4, 5}; // any list
for (int item : list) { // for each item in the list, execute the body
    System.out.println(item); // body code
}
1
2
3
4
5
#python version
array=[1, 2, 3, 4, 5]
for i in array:
    print(i)
|   #python version

illegal character: '#'



|   array=[1, 2, 3, 4, 5]

illegal start of expression

Explanation:

  • in the above loop:
    • int item : list - this line is saying that for each item in the list, execute code below
    • System.out.println(num); - this line is the body code.

Fun For Loop Hack:

Create a program that iterates through a list of numbers (int_list = {0, 4, 51, 83, 92, 10, 123, 145}) using both a for loop and a for each loop, then split the numbers in the list into even/odd lists, and output them.

import java.util.ArrayList;

public class EvenOddSplit {
    public static void main(String[] args) {
        int[] intList = {0, 4, 51, 83, 92, 10, 123, 145};
        
        ArrayList<Integer> evenList = new ArrayList<>();
        ArrayList<Integer> oddList = new ArrayList<>();
        
        for (int i = 0; i < intList.length; i++) {
            if (intList[i] % 2 == 0) {
                evenList.add(intList[i]);
            } else {
                oddList.add(intList[i]);
            }
        }

        ArrayList<Integer> evenListForEach = new ArrayList<>();
        ArrayList<Integer> oddListForEach = new ArrayList<>();
        
        for (int num : intList) {
            if (num % 2 == 0) {
                evenListForEach.add(num);
            } else {
                oddListForEach.add(num);
            }
        }

        System.out.println("For loop - Even list: " + evenList);
        System.out.println("For loop - Odd list: " + oddList);
        System.out.println("For each loop - Even list: " + evenListForEach);
        System.out.println("For each loop - Odd list: " + oddListForEach);
    }
}

EvenOddSplit.main(null);
For loop - Even list: [0, 4, 92, 10]
For loop - Odd list: [51, 83, 123, 145]
For each loop - Even list: [0, 4, 92, 10]
For each loop - Odd list: [51, 83, 123, 145]
2
15


Iteration: 0

Current Velocity: 2, 2