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?

2
  • The variable p ranges over the array ps. You can play around with it a little to see how it works, e.g. print the value of p in the loop.
    – Juho
    Apr 12, 2015 at 10:58
  • this is enhanced for loop. p is a local variable Apr 12, 2015 at 11:21

4 Answers 4

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]++;
}
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]++;
}

        
2
  • p is not the index its the elements of array ps
    – singhakash
    Apr 12, 2015 at 11:27
  • @singhakash , I was trying to explain him For-Each loop, how counter is incremented , not going on logical explaination ,still editing it !! Apr 12, 2015 at 11:30
0

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

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]++;
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.