Home > Back-end >  Why am I not getting the minimum value in an array JAVA?
Why am I not getting the minimum value in an array JAVA?

Time:10-21

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

CodePudding user response:

The size of mark array is 3 in the above example

 int[] marks = new int[n   1];

Let total number of marks is (n) : 2

We are creating the array with size of 3.

By default value for int primitives in java is 0

marks array is created with size 3

{56, 56, 0}

As per the logic the minimum value among these three elements are 0

CodePudding user response:

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.

  • Related