For-Each Loop


Collapse Content

If all you had were if-statements and while loops to control your program, your code could accomplish almost everything more 'powerful' code could do. However, it would take longer and be less clear. Programming languages provide additional features to help people write shorter clearer code.

There are several features and 'shortcuts' in Java that may not provide you with new powers, but they let you write shorter code in a clearer manner. We will go through a few of them.

The For-Each Loop

Let's say you have an array called array1:

array1 = {1,2,3,4};

For Loops are often used to iterate through a collection, including the simple array. For example, if you wanted to print out every element in array1, you could use this code:

for(int i=0; i<array1.length; i=i+1){ 
  System.out.println(array1[i]);
} 

Which will produce the following output:

1
2
3
4

Notice that you just wanted to access each item in the array, and did not care about the item's array index. These types of cases are very common, so Java introduced the for-each loop, which provides access to each element in a collection without requiring an index variable. This is its basic format:

for (type variable : array) {
    //do stuff.. 
}

The for-each loop header simply declares a variable to hold each element in the array and states the array it will go through.

The previous basic for-loop code could be replaced with this:

 for(int num : array1){
   System.out.println(num);
 }

This loop header can be read in English as:

for each num in array1

The variable num will be assigned to each element in the array as the loop operates, so you don't need to use an index to access the array. Java will use an index behind-the-scenes to go through the array for you. This is a simple shortcut, but it can make your code just a little clearer.

When to use the for-each loop

You should use the for-each loop instead of the "basic" for-loop when possible, i.e. when you want to access all the elements in an array and do not care about their index value. You saw one example above, here are some others:

  • Sum all the values of an array.
  • Find the largest value in an array (as seen here).
  • Search through an array to check if a value is there, without caring where it is.

When you need the basic for-loop

However, sometimes you need to keep track of the index yourself, so you'll need to use the basic for-loop. These are some operations where the for-each loop won't work:

  • change the values of an array's elements, such as when setting it up.
  • go through the array in a different manner, such as backwards.
  • refer to previous array element within the loop body, such as when comparing the elements.
  • find the location of an item in the array, such as a search that returns the index value of the desired element.

In addition, the basic for loop is often used to go through numbers without any array, such as a range of numbers seen in Loops and Loopy Thinking.

Coding Challenge

Go back to the challenges in the following nodes, and replace the basic for-loops with for-each loops where it makes sense to.

Challenge

The for-each loop can be used to go through an array of any type. Create the header for a for-each loop which goes through the String array called words. Use the variable word to hold each element in the array.

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Challenge

Which of the following tasks should use a for-each loop?

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Comments

  • Why is (1) incorrect? Can not I write :

    for(int num : array1){
    if(num%2!=0 && num<200){
    System.out.println(num);
    }
    }

  • @Lukas, there's no array to go through. And if there was, num would be set to the values in the array, since it's a for-each loop, which is probably different than 1 to 200.

  • I don't really understand fully this challenge... and I'm getting frustrated trying to do this simple task.

    Here's my code:

    String word; for(int num : words){ word+=words[num] };

    I find it really hard to write code in that little field.

  • In the first challenge, you just need to declare the 'header' for the for loop. Since it goes through a String array you'll need to declare the variable as a String.

Contact Us
Sign in or email us at [email protected]