Largest element in array, variable query

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • heiro1
    New Member
    • Jan 2013
    • 29

    Largest element in array, variable query

    Hello All,

    I was curious as to why the for loop in the example below, starts col = 1 instead of col = 0. Are they doing that just for this example because the largest value is stored in column 0 (the first column)? Also, I don't understand why the inequality sign is < instead of > because I am looking at it like:

    If the largest value > the current value being evaluated in a particular iteration, then the largest value's address equals that column's memory location.

    Since the sign is < though, I don't follow it's logic. Anyway, the example is below, any clarity offered is humbly appreciated.

    The following for loop determines the largest element in row number 4:


    Code:
    row = 4;
    largest = matrix[row][0]; //Assume that the first element of the row is the largest.
                              
    for (col = 1; col < NUMBER_OF_COLUMNS; col++) if (largest < matrix[row][col])
    largest = matrix[row][col];
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Code:
    row = 4;
    largest = matrix[row][0]; //Assume that the first element of the row is the largest.
                              
    for (col = 1; col < NUMBER_OF_COLUMNS; col++) if (largest < matrix[row][col])
    largest = matrix[row][col];
    The example says ASSUME the largest element is the first element of the row. That would be col 0. Therefore, your loop needs to compare the other elements (starting with col 1) until you reach the end of the row.

    Remember, an array with 5 columns contains elements numbered 0 through 4. Therefore, NUMBER_OF_COLUM NS is like the 5 and you want to stop the loop on 4. Therefore, your run the loop from 1 to <NUMBER_OF_COLU MNS.

    When you compare elements you are not comparing their addresses. You are comparing the value of the column. In this case, an assumtion is made that element 0 has the biggest value. So you set largest to the value of element 0.

    Then inside the loop you compare each of the other columns to largest. Anytime that largest is less then the value in the column, you change the value of largest to the value of that column. When the loop completes largest has the biggest value in the array but you don't know what element it is.

    Comment

    Working...