108k views
5 votes
Write an algorithm to print the minimum and maximum of an integer array. Your need to pass the array as a parameter. Since we cannot return two values (in this case, minimum and maximum), just print them inside the method. You are allowed to use only one loop. i.e. you are not allowed to traverse the array twice. Note: You can write a Java method instead of pseudo-code but pseudo-code is preferred. Following is a template to start your pseudo code. MinMax(A) min

User Navyblue
by
5.4k points

1 Answer

5 votes

Answer:

See explaination

Step-by-step explanation:

MinMax.java

import java.util.*;

public class MinMax

{

static void MinMax(int[] arr)

{

int Min=arr[0]; // initializinf min and max with 1st value of array

int Max=arr[0];

for(int i=0;i<arr.length;i++) // iterating loop only once

{

if(arr[i]>Max) // checking max value

{

Max=arr[i];

}

if(arr[i]<Min) // checking min value

{

Min=arr[i];

}

}

System.out.println("Min Number is "+Min); //printing min value

System.out.println("Max Number is "+Max); //printing max value

}

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter N value: "); // taking n value

int n=sc.nextInt();

int[] arr=new int[n];

System.out.println("Enter N elements:"); // taking n elements into array

for(int i=0;i<n;i++)

{

arr[i]=sc.nextInt(); // each element into the array

}

MinMax(arr); // calling MinMax() method.

}

}

User John Garland
by
5.1k points