-1

Can someone please explain to me how for(int current : values) works. Assuming we have a method like this. Thanks

public int count(int[] values, int value)
{
    int count = 0;
    for (int current : values)
    {
    if (current == value)
        count++;
    }
    return count;
}
Ajay S
  • 48,003
  • 27
  • 91
  • 111
The Future
  • 55
  • 1
  • 5
  • 8
    First link... http://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work – zch Apr 13 '13 at 15:35

5 Answers5

3

It is equivalent to:

for (int i = 0; i < values.length; i ++) {
    int current = values[i]
    ...
}

It is called an enhanced for loop. (Other programming languages may use for ... in or foreach, but they mean the same thing.)

Here is an article on the Oracle website about it.

tckmn
  • 57,719
  • 27
  • 114
  • 156
0

It loops over all the elements in the values array. It's the same idea as this, only without an index variable:

for (int i = 0; i < values.length; ++i) {
    int count = 0;
    if (current == values[i])
        count++;
    return count;
}

You can think of it as a "for each" loop. In other words, for each element in values array, do this loop.

dcp
  • 54,410
  • 22
  • 144
  • 164
0
for(int current : values)

is a for-each loop ,which is similar to :

for(int i =0 ; i< values.length; i++)
Achintya Jha
  • 12,735
  • 2
  • 27
  • 39
0

It is not simply a for, it is a foreach, and it works like this:

public int count(int[] values, int value)
{
    int count = 0;
    for (int i=0;i<values.length;i++)
    {
    current = values[i];
    if (current == value)
        count++;
    }
    return count;
}
BackSlash
  • 21,927
  • 22
  • 96
  • 136
  • ok, after assigning the value of values[0] into current....does the if statement check if current equals the whole array of values before incrementing i and assigning values[1] into current – The Future Apr 13 '13 at 15:55
  • Absolutely **not**. It only checks if `current` equals to the `value` you have in the method parameters – BackSlash Apr 13 '13 at 15:57
0

The for-each and equivalent for statements have these forms. The two basic equivalent forms are given, depending one whether it is an array or an Iterable that is being traversed. In both cases an extra variable is required, an index for the array.

For-each loop

for (type var : arr) {
   body-of-loop
}

Equivalent for loop

for (int i = 0; i < arr.length; i++) { 
   type var = arr[i];
   body-of-loop
}

Update:

Turbo C does not support for each loop. But same you can achieve using for loop constructs of C.

Read here : For Each Loop supports in languages

Ajay S
  • 48,003
  • 27
  • 91
  • 111