Find Largest Value In Array

This little script will help you find the largest value in an array. Let's say we have an array of player scores like so;

// Initialize variables
playerScores[0] = 10;
playerScores[1] = 15;
playerScores[2] = 5;
playerScores[3] = 20;

Of course we could check this by performing an if statement for each value, but this is unprofessional and very very messy. Let's say you have 1000 players, you'd have to accommodate 1000 if statements with 1000 checks in each. You're not going to want to do that.

The easy way to do it is by checking each value against the current highest value and then if it is larger, update the largest value.

int maxValue = 0;
 
// Loop through each array element
for (int i = 0; i < playerScores.Length; i++)
{
    // Check if this is larger than our stored one
    if (playerScores[i] > playerScores[maxValue])
    {
        // Save this as the largest
        maxValue = i;
    }
}

With any luck, the variable "maxValue" now contains the index of the largest value in the array. Note that I said INDEX. It does NOT contain the largest value itself. To get that of course just use playerScores[max].

~ knighty (Graeme Pollard - moc.liamg|33thgink#moc.liamg|33thgink)

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.