Skip to content
Advertisement

Why am I not getting the minimum value in an array JAVA?

import java.util.*;
public static void main(String[] args) {
    
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter the size ??");
    int n = sc.nextInt();
    int[] marks = new int[n + 1];
    
    for (int i = 0; i < n; i++) {
        System.out.println("Enter " + i + " number ??");
        marks[i] = sc.nextInt();
    }
    
    System.out.println("The  following numbers are : ");
    for (int j = 0; j < marks.length - 1; j++) {
        System.out.println(marks[j] + " ");
    }
    
    int max = marks[0];
    int min = marks[0];
    int s = marks.length;
    for (int i = 0; i < s; i++) {
        if (marks[i] > max) {
            max = marks[i];
        }
        if (marks[i] < min) {
            min = marks[i];
        }
    }
    
    System.out.println("Max is " + max + " Min is " + min);
}

Output:

Enter the size ??2
Enter 0 number ??
56
Enter 1 number ??
56
The  following numbers are : 
56 
56 
Max is 56 Min is 0

Advertisement

Answer

Hello and welcome to StackOverflow. Next time, febore you jump into the internet for help, please try this approach. It will solve your problem much quicker.

for (int i = 0; i < s; i++) {
    System.out.println("DEBUG: number in index " + i + " is " + marks[i]);

    if (marks[i] > max) {
        System.out.println("DEBUG: number is greater than current max " + max);

        max = marks[i];
    }
    if (marks[i] < min) {
        System.out.println("DEBUG: number is smaller than current min " + min);

        min = marks[i];
    }
}

This process is called “debugging”. It can be done by adding spurious amount of logging like above or by stepping through the code with a debugger.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement