Write a Java program to find the maximum and minimum value of a 1-d array.
import java.util.*;
class App {
public static int getMaxValue(int[] numbers) {
int maxValue = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > maxValue) {
maxValue = numbers[i];
}
}
return maxValue;
}
public static int getMinValue(int[] numbers) {
int minValue = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] < minValue) {
minValue = numbers[i];
}
}
return minValue;
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter size of array: ");
int n = keyboard.nextInt();
int[] numbers = new int[n];
for (int i = 0; i < n; i++) {
System.out.print("Enter number " + (i + 1) + ": ");
numbers[i] = keyboard.nextInt();
}
System.out.println("The minimum value of a 1-d array: " + getMinValue(numbers));
System.out.println("The maximum value of a 1-d array: " + getMaxValue(numbers));
keyboard.close();
}
}
Comments
Leave a comment