Hi @all!
I have a array with three numbers:
num[0] = 5
num[1] = 2
num[2] = 5
I need to find out which of these numbers are the largest ones, it could be one, two or all of them, and need the index. Here for example "0 and 2". What's the best (most compact) way for that?
Thanks a lot.
rob

Edited by rob211: n/a

4
Contributors
8
Replies
9
Views
6 Years
Discussion Span
Last Post by rob211

Use a for loop to look at the numbers one at a time and save the largest ones.
If you are saving the indexes and there can be more than one, you will need another array to save the indexes in.

``````int max = num[0];
for ( i=1; i<=2; i++ )
{
if(num[i] > max)
{
max = num[i];
}
}

for ( i=0; i<=2; i++ )
{
if(num[i] == max)
{
System.out.println(i+": "+num[i]);
}
}``````

Hi kolibrizas
Your help, advice, and assistance are very welcome here. But please don't just post solutions to people's homework for them to copy & paste. All they learn from that is how to cheat. Give them guidance that allows them to learn how to do it for themselves. Thanks.

Hi kolibrizas
Your help, advice, and assistance are very welcome here. But please don't just post solutions to people's homework for them to copy & paste. All they learn from that is how to cheat. Give them guidance that allows them to learn how to do it for themselves. Thanks.

Sorry about that. Didn't think of that. Should I edit/remove my post? :)

Maybe an edit to explain why/how that code works - but don't worry, there's no harm done this time. :)

For some reason I cannot see Edit button at my post :( Guess I will leave it like that. Thanks for a lesson, will try to do better from now :)

P.S. For this post I do see an edit button o.O

Edited by kolibrizas: n/a

Yeah, the edit button is only available for (I think) 30 mins after the original post. Anyway, don't worry, it's OK.

Thank you very much, it was very helpful for me, and it is no homework, it was just for fun...