Today, this article will share with you an example of how to get the maximum and minimum values in an array. It is very suitable for Java beginners to review the basic usage of arrays and the use of flow control statements. The details are as follows:
This program mainly finds the maximum and minimum values in the array
public class TestJava4_3 { public static void main(String args[]) { int i,min,max; int A[]={74,48,30,17,62}; // Declare integer array A and assign initial value min=max=A[0]; System.out.print("The elements of array A include: "); for(i=0;i<A.length;i++) { System.out.print(A[i]+" "); if(A[i]>max) // Determine the maximum value max=A[i]; if(A[i]<min) // Determine the minimum value min=A[i]; } System.out.println("/The maximum value of the array is: "+max); // Output the maximum value System.out.println("The minimum value of the array is: "+min) ; // Output the minimum value } }
The program outputs:
The elements of array A include: 74 48 30 17 62 The maximum value of the array is: 74 The minimum value of the array is: 17
The program description is as follows:
1. Line 6 declares the integer variable i as the loop control variable and the index of the array: it also declares the variable min to store the minimum value and the variable max to store the maximum value.
2. Line 7 declares the integer array A, which has 5 array elements, and their values are 74, 48, 30, 17, and 62 respectively.
3. Line 9 sets the initial values of min and max to the first element of the array.
4. Lines 10 to 18 output the contents of the array one by one, and determine the maximum and minimum values in the array.
5. Lines 19~20 output the maximum and minimum values after comparison. After setting the initial values of the variables min and max to the first element of the array, compare them with each element in the array one by one. If it is smaller than min, the value of the element will be assigned to min for storage, so that the content of min will be kept minimum; similarly, when the element is larger than max, the value of the element will be assigned to max storage, so that the content of max will be kept maximum. . After the for loop is executed, it means that all elements in the array have been compared. At this time, the contents of the variables min and max are the minimum and maximum values.
The code described in this article is a relatively basic sample program. I believe it still has certain reference value for Java beginners.