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.
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.
for(int i =0; i < 20 && i < prices.length; i++)
This will loop through 20 times, i.e. first twenty elements of the array.
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++)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With