In: Computer Science
Write a Java program that creates an array with 20 random numbers between 1 and 100, and passes the array to functions in order to print the array, print the array in reverse order, find the maximum element of the array, and find the minimum element of the array.
The prototype of the methods:
public static void printArray(int arr[])
public static void printArrayReverse(int arr[])
public static int searchMax(int arr[])
public static int searchMin(int arr[])
Sample output:
Random Array: [17 67 49 26 24 26 70 42 2 22 20 87 42 73 33 21 87 37 84 66]
Random Array in Reverse Order: [66 84 37 87 21 33 73 42 73 42 87 20 22 2 42 70 26 24 26 49 67 17]
Max Value of the Array: 87
Min Value of the Array: 2
Solution :
Following is the Java code for the above problem with output :
import java.util.Random;
public class Program {
public static void printArray(int arr[])
{ System.out.println("\n");
for(int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+" ");
}
}
public static void printArrayReverse(int arr[])
{ System.out.println("\n");
for(int i = arr.length-1; i >=0; i--) {
System.out.print(arr[i]+" ");
}
}
public static int searchMax(int arr[])
{
int max = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] > max)
max = arr[i];
}
return max;
}
public static int searchMin(int arr[])
{
int min = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] < min)
min = arr[i];
}
return min;
}
public static void main(String[] args) {
Random rd = new Random(); // creating Random object
int[] arr = new int[20];
for (int i = 0; i < arr.length; i++) {
arr[i] = rd.nextInt(100); // storing random integers in an array
}
printArray(arr);
printArrayReverse(arr);
System.out.println("\n");
System.out.println(searchMax(arr));
System.out.println("\n");
System.out.println(searchMin(arr));
}
}
Code demo :
Output :