Home > database >  Determing biggest number in array
Determing biggest number in array

Time:11-22

Can someone explain this code to me? So i´ve got an array which is filled with int numbers. Now the Code is supposed to determine which int number is the biggest. But I don´t understand the if command in this context.

max = 0; for(int i = 0; i < testArray.length; i  ) {
        if(max < testArray[i]) {
            max = testArray[i];
        }
    }

CodePudding user response:

Before the loop we declare an integer called max. This variable will represent the highest value we have found. We then start a for-loop that iterates over every element of the array. For every value, we compare it to our max variable. If max is lower than the value we are inspecting then the value is the highest value we have found so far, so we assign the value to the max variable. After we have iterated over the entire array, the max variable will contain the highest value we have found.

int max = 0; // A variable that represents the highest value we have found
for(int i = 0; i < testArray.length; i  ) {
        if(max < testArray[i]) { // If max is lower than the current value...
            max = testArray[i]; // ...assign the current value to max
    }
}

CodePudding user response:

first let's create array [10, 100, 25, 57, 63, 96] and start our loop the max = 0 where the first int will be 10 the if will test is 0 < 10 true it will go and make the max = 10 the second time will check if the 10 < 100 which is true it will do the statement and max will be 100 then the third will check if 100 < 25 which is false and keep until the end of loop

  • Related