-2

I'm trying to figure how to find the largest number in an array of random numbers.

So far I cant manage to get it right.

Its an array[50] and the random, numbers are between 0-100.

Thanks!

prmottajr
  • 1,816
  • 1
  • 13
  • 22
RanTz
  • 15
  • 5

5 Answers5

7

Loop through the array and keep track of the largest number found already in an int variable.

Martin Dinov
  • 8,757
  • 3
  • 29
  • 41
1
public int findMax(int[] numbers)
{
    int max = 0;

    for (int i = 0; i < numbers.length; ++i)
        if (numbers[i] > max) max = numbers[i];

    return max;
}

(You can also initialize max to int.MIN_VALUE or something if it helps behave more suitably in the case where an empty array is passed in.)

TypeIA
  • 16,916
  • 1
  • 38
  • 52
  • Would the downvoter please comment? Thanks. – TypeIA Dec 26 '13 at 19:50
  • You've deprived the OP of any learning opportunity. Better would be to help the OP arrive at this solution himself. – dnault Dec 26 '13 at 19:50
  • 1
    @dnault Learning opportunities are up to him, not me. Personally I find studying example code extremely useful and informative when I'm trying to learn something new. If he just pastes in the answer and moves on, he made that choice, not me. – TypeIA Dec 26 '13 at 19:54
  • Fair point about learning from example code. Please have your vote back along with my apologies. – dnault Dec 26 '13 at 20:14
0

Use:

java.utils.Arrays.sort(yours_array);
int largest = yours_array[yours_array.length - 1] ;
Vyacheslav Shylkin
  • 9,741
  • 5
  • 39
  • 34
0

Collections.max and you can use it as follows with a raw array:

List<Integer> triedArray = new ArrayList<Integer>();
ArrayUtils.addAll(intArray);

This does add a dependency on commons-lang, though.

hd1
  • 33,938
  • 5
  • 80
  • 91
0

Assuming the int[] is named array

Try to use a loop like the following:

int biggest = array[0]
for(int a = 1; a < array.length; a++){
    if(array[a] > biggest){
        biggest = array[a]
    }
}

At the end, your variable biggest will hold the largest value in the array.