I am learning about arrays and was attempting to code a program to find the greatest Integer in an array. The program isn't giving me the intended solution
My code:
import java.util.*;
public class GreaterInt{
public static void main(String[] args){
System.out.println("Enter the size of the array");
Scanner sc = new Scanner(System.in);
//creating the dimesion for array
int size = sc.nextInt();
System.out.println("Enter the values inside the array");
// Creating an array
int [] numbers = new int [size];
//entering the values in the array
for (int i = 0; i < size; i ){
numbers [i] = sc.nextInt();
}
int max = Integer.MAX_VALUE;
int min = Integer.MIN_VALUE;
for (int i = 0; i < numbers.length; i ){
if (numbers[i] < min){
min = numbers[i];
}
if (numbers[i] > max){
max = numbers[i];
}
}
System.out.println("The minimum value in the list of numbers is" max);
System.out.println("The maximum value in the list of numbers is" min);
}
}
The result I am getting:
Enter the size of the array
5
Enter the values inside the array
2
4
2
6
1
The minimum value in the list of numbers is2147483647
The maximum value in the list of numbers is-2147483648
CodePudding user response:
Your initialisation is incorrect. You are initialising your min and max variables like
int max = Integer.MAX_VALUE;
int min = Integer.MIN_VALUE;
Although it should be the opposite
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
In the 1st if block where you are trying to find the minimum number, since min is already equal to Integer.MIN_VALUE, no value of numbers[i] will be lower than that and the if condition will never be true.
if (numbers[i] < min) {
min = numbers[i];
}