15

I am new to Java. I was reading someone's solution to a question and I encountered this:

        int[] ps = new int[N];
        for (int i = 0; i < N; i++)
            ps[i] = input.nextInt();

        int[] counts = new int[1005];
        for (int p : ps)
            counts[p]++;

What do the last two lines do?

Raphael
  • 9,779
  • 5
  • 63
  • 94
ksraj98
  • 342
  • 1
  • 2
  • 10

4 Answers4

10

This is a for-each loop. It sets p to the first element of ps, then runs the loop body. Then it sets p to the second element of ps, then runs the loop body. And so on.

It's approximately short for:

for(int k = 0; k < ps.length; k++)
{
    int p = ps[k];
    counts[p]++;
}
user253751
  • 57,427
  • 7
  • 48
  • 90
3

For-each loop (Advanced or Enhanced For loop):

The for-each loop introduced in Java5. It is mainly used to traverse array or collection elements. The advantage of for-each loop is that it eliminates the possibility of bugs and makes the code more readable.

Syntax

for(data_type variable : array | collection){}  

Source :Java For Each Loop

In your case this loop is iterating the Array

Equivalent Code without For Each Loop

for (int i=0;i<ps.length;i++){
int p=ps[i];
counts[p]++;
}

        
Community
  • 1
  • 1
Neeraj Jain
  • 7,643
  • 6
  • 34
  • 62
0

That's a for loop. for (int p : ps) iterates over ints in the ps int array

Crazyjavahacking
  • 9,343
  • 2
  • 31
  • 40
0

The line is iterating over each index of array an taking out its value in a sequence in a p varable.You can check by

for (int p : ps){            // if ps is {1,2,3}
   System.out.print(p+" ");  // it will print 1 2 3
   counts[p]++;
}
singhakash
  • 7,891
  • 6
  • 31
  • 65