Finding the Maximum or Minimum in Java.

One of the more fundamental concepts to uderstand in programming is in finding the maximum or minumum in an array. Suppose you want to find the largest number in an array. Keep a candidate for the maximum. If you find an element with a larger value, then replace the candidate with that value. When you have reached the end of the array list, you have found the maximum. There is just one problem. When you visit the beginning of the array, you don’t yet have a candidate for the maximum. One way to overcome that is to set the candidate to the starting element of the array and start the comparison with the next element.

1
2
3
4
5
6
7
8
9
10
11
//creating an array with 5 numbers
int[] numbers = {1, 3, 5, 7, 9};
//creating a variable and setting it to array position 0
int largestYet = numbers[0]
//looping through the rest of the array to find maximum num
for(int i = 0; i < numbers.lenght; i++)
{
int a = numbers[i];
if(a > largestYet) 
largestYet = a;
}
Share This!

Leave a Reply

Your email address will not be published.