In: Computer Science
#4 You need to write a class MinMax with a method minmax that takes an array of integers as a parameter and returns min and max simultaneously (using one method and one call). (java oop)-> laboratory work
Compile using -> javac MinMax.java
Run using -> java MinMax
import java.util.*;
import java.io.*;
public class MinMax
{
public static void main(String[] args)
{
int n;
Scanner sc = new Scanner(System.in);
System.out.print("Enter size of array ");
n = sc.nextInt();
int A[] = new int[n];
System.out.println("Enter array's elements =>");
for(int i = 0; i < n; i++)
{
A[i] = sc.nextInt();
}
int[] ans = new int[2]; //to store the answers as min and max
respectively at index 0 and 1
ans=minmax(A,n);
System.out.println("Max and min values are "+ans[0]+" ans
"+ans[1]);
}
public static int[] minmax(int A[],int n)
{
int[] ans = new int[2];
int max=A[0];
int min=A[0];
for (int i=0;i<n;i++)
{
if(A[i]>max)
{
max=A[i];
}
if(A[i]<min)
{
min=A[i];
}
}
ans[0]=max;//store max at index 0 of ans[] array
ans[1]=min;//store min at index 1 of ans[] array
return ans;//return answer
}
}
Output -
Enter size of array 5
Enter array's elements =>
4 2 3 5 1
Max and min values are 5 ans 1