Daniel
Daniel

Reputation: 13

How to Find Max Value in Entire 2D Array (Processing)

I have a 2D array that has random values assigned to it. I am looking to find the highest value in this 2D array so I can display it as text.

I was trying to use this loop to do this, however, it only gives me the last value in the array.

  for (iRow=0; iRow<10; iRow++)
  {
    for (iCol=0; iCol<4; iCol++)
    {
      iHighestMark=0;

      if (iArray[iRow][iCol]>iHighestMark)
      { 
        iHighestMark=iArray[iRow][iCol];

      }
    }
  }

Any advice would be greatly appreciated :)

Upvotes: 1

Views: 458

Answers (2)

As p.phidot was saying, you need to initialize the variable outside for loop or else, the max value will reset to zero every time the program goes through the loop. The new code fixes the problem, but if all the numbers in the matrix are negative, I advise this change in the code:

iHighestMark = Integer.MIN_VALUE;

for (iRow = 0; iRow < 10; iRow++) {

   for (iCol = 0; iCol < 4; iCol++) {

      if (iArray[iRow][iCol]>iHighestMark) {

         iHighestMark=iArray[iRow][iCol];

      }
   }
}

Upvotes: 1

p._phidot_
p._phidot_

Reputation: 1950

 iHighestMark=0;

 for (iRow=0; iRow<10; iRow++)
  {
    for (iCol=0; iCol<4; iCol++)
    {

      if (iArray[iRow][iCol]>iHighestMark)
      { 
        iHighestMark=iArray[iRow][iCol];

      }
    }
  }

Upvotes: 0

Related Questions