Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop over the first 20 elements of an array in Java

Tags:

java

arrays

loops

I have this loop here

 for(int i =0; i < prices.length; i++)
  {
        if(prices[i]>largest)
        {
            largest = prices[i];
        }

        else if(prices[i]<smallest)
        {
            smallest= prices[i];
        }
  }

which loops through the whole array and finds the min and max value. Say I wanted to only loop through the first 20 elements how do I do that? I have tried along the lines of putting a nested loop in under this for loop and seeing if I come across it but I can't.

like image 901
user1816464 Avatar asked Feb 04 '13 22:02

user1816464


3 Answers

You could just add the requirement to the loop control condition:

for(int i =0; i < prices.length && i < 20; i++)

This would check the first 20 elements where ther are more than 20 in the array, but the whole array if there are less than 20 items.

like image 80
Andrew Cooper Avatar answered Sep 21 '22 17:09

Andrew Cooper


for(int i =0; i < 20 && i < prices.length; i++)

This will loop through 20 times, i.e. first twenty elements of the array.

like image 22
user2033853 Avatar answered Sep 20 '22 17:09

user2033853


5 answers and they all have a double comparison in the loop?

No wonder, Java programs run so slowly...

The correct way to do such a loop is:

 for(int i = 0, len = Math.min(prices.length, 20); i < len; i++)

moving the comparison between length and 20 out of the loop and evaluating the loop-condition therefore twice as fast. (ignoring what the JIT might or might not be doing)

Also, you have to initialize largest/smallest with the first element (or you get invalid values, if there is only one element in the array due to the else), and then you can skip the first element in the loop, making it even "faster":

 largest = prices[0];
 smallest = prices[0];
 for(int i = 1, len = Math.min(prices.length, 20); i < len; i++)
like image 27
BeniBela Avatar answered Sep 20 '22 17:09

BeniBela