What is wrong with my for loop for determining mid-max in a 2D array? C++ Not assigning new value to the variable

Viewed 47
for (i = 0, i < NUM_ROWS; i++;){
    for (j = 0, j < NUM_COLS; j++;){ 
        if (milesTracker[i][j] > maxMiles)
            maxMiles = milesTracker[i][j];
            
        if (milesTracker[i][j] < minMiles)
            minMiles = milesTracker[i][j];
    }
}

maxMiles & midMiles both given/initialized at 0 before the nested loop. When I run it (cout << minMiles), it only gives back a zero for either, no matter the inputs.

Where is my logic flawed here? It should go:

  1. Go through each number in the array
  2. First time, is it larger than zero, if so then make it the new number.
  3. Loop, repeat, until over.

Currently having to pay for my sins from CompSci 1 in CompSci 2, so I'm just trying to review what I never learned...

1 Answers

your for loop declarations have mistakes. A for loop requires

for (index; range; increment)

and those segments to be seperated by the semicolon. right now you have a comma-operator in the index clause, meaning both index and the range checks i = 0, i < NUM_ROWS and j = 0, j < NUM_COLS appear in in the first segment, and therefore the < checks are effectively ignored (how does the comma operator work?). So i++ and j++ are now at the range check instead , and those will always result in 0 because i and j, respectively, start at 0.

You should change your for loops to look like this:

for (i = 0; i < NUM_ROWS; i++){
    for (j = 0; j < NUM_COLS; j++){ 
        //...
Related