I know that the below code will give the greatest value in an Array, but why?
public class Practice {
public static int greatest(ArrayList<Integer> list) {
int greatest = list.get(0);
for(int i: list){
if(i > greatest){
greatest = i;
}
}
return greatest;
}
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(3);
list.add(5);
list.add(2);
list.add(7);
list.add(8);
System.out.println("The greatest number is: " + greatest(list));
}
}
If it is comparing the first value indexed in the list to another value that is greater than it while looping, wouldn't it would choose 5 instead of 8? How does it know to choose 8 instead of 5?
Thank you very much.