Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in a for-loop, what does the (int i : tall) do, where tall is an array of int [duplicate]

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+=;
    }
    }
}
like image 383
Makri Avatar asked Oct 14 '13 10:10

Makri


3 Answers

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 ...

like image 100
Konstantin Yovkov Avatar answered Oct 21 '22 07:10

Konstantin Yovkov


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.

like image 40
Maroun Avatar answered Oct 21 '22 07:10

Maroun


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?

like image 38
Suresh Atta Avatar answered Oct 21 '22 07:10

Suresh Atta