user1816464 user1816464 - 7 months ago 36
Java Question

Loop over the first 20 elements of an array in Java

I have this loop here

for(int i =0; i < prices.length; i++)
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.