13

As the header says, I was tipped by some people that if I wanted to print the sum of everything in an array of numbers, I should use the above-mentioned parameter for a for-loop (code will follow if further explanation is needed). But what is the exact definiton of what that does? The :-part I mean. Is it; for every number i in the array tall?

import java.util.*;

class Uke36{
    public static void main(String[]args){

    Scanner input=new Scanner(System.in);
    int[] tall=new int[5];

    for (int i=0; i<=4; i++){
        System.out.println("Vennligst oppgi det " + (i+1) + ". tallet: ");
        tall[i]=input.nextInt();
    }
    int sum = 0;
    for(int i : tall){
        sum+=;
    }
    }
}
Makri
  • 331
  • 2
  • 4
  • 15

7 Answers7

11

This is how for-each loops are represented in Java.

for (int i : tall) {
  sum += i;
}

Read it as: For each integer i in the array called tall ...

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
  • Ah, okay. Thanks! Then, another small question: Below it I have edited and now wrote sum+=i; does this mean that for every integer i in the array tall, it should add that value to the already-existing integer sum? – Makri Oct 14 '13 at 10:22
  • 2
    @Makri `sum += i;` that menas `sum= sum+i`; – Suresh Atta Oct 14 '13 at 10:25
2

It's enhanced loop. It was introduced in Java 5 to simplify looping. You can read it as "For each int in tall" and it's like writing:

for(int i = 0; i < tall.length; i++)
   ...

Although it's simpler, but it's not flexible as the for loop.. It's good when you don't really care about the index of the elements.

More reading.

Maroun
  • 94,125
  • 30
  • 188
  • 241
2

That enhanced for loop equals to

for (int i=0; i < tall.length; i++) {
    System.out.println("Element: " + tall[i]);
}

The below form

 for(int i : tall){

Is the short hand form the classical for loop.

Note:

But there is a condition to use the above form

Form Language specification

The type of the Expression must be Iterable or an array type (§10.1), or a compile-time error occurs.

Here the docs from oracle

Finally

 int sum = 0;
    for(int i : tall){
        sum+=;  // sum = sum+i
    }

That means adding the all elements in the array.

If it Collection, See how that loop converts :What are for-each expressions in Java translated to?

Community
  • 1
  • 1
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

for(int i : listOfInt)

This is the advanced(enhanced) for loop, also called the for-each loop, which iterates over each element of the list provided on the right hand side of the :, assigning each value iteratively to the variable on the left of the :.

It basically means, for each element in the array/arraylist (in your case, its an array called tail).

Have a look at the docs here for more detailed info.

Rahul
  • 44,383
  • 11
  • 84
  • 103
1

“Enhanced” for loops

INTERMEDIATE

The usual way to step through all the elements of an array in order is with a "standard" for loop, for example,

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

The so-called enhanced for loop is a simpler way to do this same thing. (The colon in the syntax can be read as "in.")

for (int myValue : myArray) {
    System.out.println(myValue);
}

The enhanced for loop was introduced in Java 5 as a simpler way to iterate through all the elements of a Collection (Collections are not covered in these pages). It can also be used for arrays, as in the above example, but this is not the original purpose.

Enhanced for loops are simple but inflexible. They can be used when you wish to step through the elements of the array in first-to-last order, and you do not need to know the index of the current element. In all other cases, the "standard" for loop should be preferred.

Two additional statement types, break and continue, can also control the behavior of enhanced for loops.

Copied from http://www.cis.upenn.edu/~matuszek/General/JavaSyntax/enhanced-for-loops.html

And it's a humble request to all that first try to find your answer on google

SSP
  • 2,650
  • 5
  • 31
  • 49
0

Read form the documentation:

The for statement also has another form designed for iteration through Collections and arrays This form is sometimes referred to as the enhanced for statement, and can be used to make your loops more compact and easy to read.

The following program, EnhancedForDemo, uses the enhanced for to loop through the array:

class EnhancedForDemo {
        public static void main(String[] args){
             int[] numbers = 
                 {1,2,3,4,5,6,7,8,9,10};
             for (int item : numbers) {
                 System.out.println("Count is: " + item);
             }
        }
    }

In this example, the variable item holds the current value from the numbers array. The output from this program is the same as before:

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
CloudyMarble
  • 36,908
  • 70
  • 97
  • 130
0

It is a for-each loop

   int[] arr=new int[] {1,3,5,7,8};
   for(int i:arr){
       System.out.println(i); 
   }

Out put will be

 1
 3
 5
 7
 8

But this work in JDK 1.7 and higher versions only. Early JDK version support for-each loop with Object type.

And following for loop similar to this for-each

    int[] arr=new int[] {1,3,5,7,8};
    for(int i=0;i<arr.length;i++){
        System.out.println(arr[i]);
    }
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115