gauche23
gauche23

Reputation: 67

How to get the highest and lowest value in the array in this code?

I need help to get the highest and lowest value in an array. I saw some people use Math.max and Math.min but how do you apply it? in this code?

import java.util.Scanner;
public class CaseStudy2A {
    public static void main(String[] args) {
        Scanner inp = new Scanner (System.in);
        int inpNum;
        System.out.print("Enter Number: ");
        inpNum = inp.nextInt();

        int num[]=new int [inpNum];

        int y=0;
        int accu;

            for(int x=0;x<inpNum;x++) {
                y=y+1;

                System.out.print("\nNumber [" + y + "] : ");
                accu = inp.nextInt();

                num[x]=accu;
            }
        for(int x=0;x<inpNum;x++)
        System.out.print(num[x] + " ");
    }
}

Upvotes: 0

Views: 3068

Answers (3)

P. B. M.
P. B. M.

Reputation: 262

[There was an attempt to edit my post, so I decided to improve it myself]

Introduce

int min=0, max=0;

then, after the first "for" loop, when all array values are known, do the following:

min=max=num[0];
for(int x=1; x<inpNum; x++) {
  if(num[x]<min) {
    min=num[x];
  }
  else if(num[x]>max) {
    max=num[x];
  }
}

This is faster than calling Math.min/max. Actually, this is the fastest way to compute both minimum and maximum since almost always you end up with less than 2n comparisons (where n is the array length), because when you find a new minimum you don't check for a new maximum. And that's why the ternary (?:) comparison is not used. (You also have to check that inpNum is positive.)

Upvotes: 0

MemLeak
MemLeak

Reputation: 4640

If performance is irrelevant you could create a collection from the array and use collection max and min.

If you want to solve your homework by Math.* you could use this snippet:

int max= Integer.MIN_VALUE;
int min= Integer.MAX_VALUE;
for(int x=0;x<inpNum;x++){
 max = Math.max(max,x);
 min = Math.min(min,x);

Upvotes: 4

AlexF
AlexF

Reputation: 124

I get the feeling this is homework... but there's a few ways of doing it. You can loop through each element in the array, store the first one you hit into a variable and then check each one after that to see if it's larger than the one currently stored. If it is, overwrite the variable with that one and continue. At the end you will have the largest one.

Another method would be to sort the array and then take the first and last element in it, giving you the largest and smallest.

Upvotes: 1

Related Questions