6.3 Enhanced For Loop for Arrays

The “Enhanced For Loop” is otherwise known as a for each loop. This provides a simple way to loop through iterable data structures such as arrays and lists. The syntax for this loop is as follows,

for(dataType element : array) { 
    //code to be ran on an element
}

If this syntax is unfamiliar, perhaps the Python version can be used as reference

for element in array:
    #code to be ran on element

Here’s an example of using these types of loops to calculate the sum of an Array Do note the iterated element has to be of the data type in the array.

int sum = 0;
int[] numArray = {1,2,3,4,5,6,7,8,9,10};
for(int numElement : numArray)
{
    System.out.println(numElement);
    sum += numElement;
}
System.out.println(sum);
1
2
3
4
5
6
7
8
9
10
55

Popcorn Hack: Rewrite For Loop with For Each Loop

You are working as an intern for a car sales company at their IT department. Your new task your boss gave you is to post the prices and names of the newest cars to be sold The previous IT developer couldnt get their for loop to work. Could you fix the issue?

Given the following code, rewrite the script to use a for each loop instead of the for loop and fix the problem

import java.util.HashMap;
import java.util.Map;
Map<String, Integer> carMap = new HashMap<String, Integer>();
/*
 HashMap Syntax
 Map.Entry<String, Integer> entry for iterable loops
 Refer to the iterated HashMap as carMap.entrySet()
 entry.getKey()
  entry.getValue()
*/

carMap.put("MortMobile",9999);
carMap.put("CSAwesomeCar",500);
carMap.put("ArrayceCar",5000);

for(int i=0;i<carMap.length;i++) //for the next developer: please fix this!!
{
    System.out.println(carMap[i]);
    
}
//Sample Solution
import java.util.HashMap;
import java.util.Map;
        Map<String, Integer> carMap = new HashMap<String, Integer>();

        carMap.put("MortMobile",9999);
        carMap.put("CSAwesomeCar",500);
        carMap.put("ArrayceCar",5000);
        for(Map.Entry<String, Integer> entry : carMap.entrySet())
        {
            System.out.println(entry.getKey());
            System.out.println(entry.getValue());
        }
CSAwesomeCar
500
ArrayceCar
5000
MortMobile
9999

Limitations On Enhanced For Loops

It does not allow for access to the index number of the element, You cannot modify elements of the loop You cannot get a specific index in the same way array[ i ] can

Final Hack

Finish the following code with a for each and normal for loop

int[] nums = {1,2,3,4,5,6,2000};

//loop through the array and print if the current index is even
//Sample Solution
int[] nums = {1,2,3,4,5,6,2000};

for(int i=0;i<nums.length;i++)
{
    System.out.println(nums[i] % 2 ==0);
}

for(int number : nums)
{
    System.out.println(number % 2 ==0);
}
false
true
false
true
false
true
true
false
true
false
true
false
true
true