Today, we share 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. Specifically as follows:
This program is primarily to obtain 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}; Declares an integer array A, and assigns an initial value of
min=max=a[0];
System.out.print ("element of array a includes:");
for (i=0;i<a.length;i++)
{
System.out.print (a[i]+ "");
if (A[i]>max) //Judging maximum value
max=a[i];
if (a[i]<min) //judgment minimum
min=a[i];
}
System.out.println ("\ n the maximum value of an array is:" +max); Output maximum
System.out.println ("The minimum value of the array is:" +min);//output Minimum
}
}
The program outputs the results:
The elements of the array a include: the
maximum value of the array is:
The minimum value of the arrays is: 17
The procedures are described below:
1. Line 6th declares the integer variable I as the index of the loop control variable and the array: In addition to the variable Max, which holds the minimum value of the variable min and the maximum value.
2. Line 7th declares integer array A, with 5 of its array elements, 74, 48, 30, 17, 62 respectively.
3. The 9th line will be min and Max's initial value set to the first element of the array.
4. Line 10th to 18th output the contents of the array, and determine the maximum and minimum values in the array.
5. The maximum and minimum values are compared for line 19th to 20th output. The variable min and max initial values are set to the first element of the array, and then each element is compared to the elements in the arrays. Smaller than min, the value of the element is assigned to the Min storage, so that Min's content to keep the smallest; Similarly, when the element is larger than Max, the value of the element is assigned to the Max to store, keeping Max's content to the max. When the For loop finishes, it means that all elements in the array have been compared, and that the contents of Min and Max are the minimum and maximum values.
The code described in this article is a relatively basic sample program, I believe that for beginners of Java still have some reference value.