Finding Min/Max Value of an Array

Hello everyone,

Hope this quarantine has been kind to you all.

Please help with the following program... I am trying to find the minimum and maximum values of the user input "value" in the nested for loop. I tried using an if/else

int count = 1;

if(milesTracker[count][count] > milesTracker[1][1]){
maxMiles = milesTracker[count][count]
count ++;
}
else if(milesTracker[1][1] > milesTracker[count][count]){
minMiles = milesTracker[count][count];
count ++
}

THANKS!
-------------------------------------------------------------------------------

#include <iostream>
using namespace std;

int main() {
const int NUM_ROWS = 2;
const int NUM_COLS = 2;
int milesTracker[NUM_ROWS][NUM_COLS];
int i;
int j;
int maxMiles = 0; // Assign with first element in milesTracker before loop
int minMiles = 0; // Assign with first element in milesTracker before loop
int value;

for (i = 0; i < NUM_ROWS; i++){
for (j = 0; j < NUM_COLS; j++){
cin >> value;
milesTracker[i][j] = value;
}
}


************CODE SHOULD GO HERE*********************




cout << "Min miles: " << minMiles << endl;
cout << "Max miles: " << maxMiles << endl;

return 0;
}
First, please use code tags. See http://www.cplusplus.com/articles/jEywvCM9/

Where was your if/else?

1
2
3
4
if ( milesTracker[count][count] > milesTracker[1][1] ) {
    maxMiles = milesTracker[count][count]
    count ++;
}

* What is the initial value of count?
* Why do you compare against last element of the matrix?
* Why do you compare only the diagonal elements of the matrix?

1
2
3
4
5
6
if ( milesTracker[count][count] > milesTracker[1][1] ) {
  count ++;
}
else if ( milesTracker[1][1] > milesTracker[count][count] ) {
  count ++
}

What if milesTracker[1][1] == milesTracker[count][count]? The count won't advance.


2D array is actually a continuous block and can be accessed like it were 1D:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// my first program in C++
#include <iostream>
#include <algorithm>

int main()
{
  const int NUM_ROWS = 2;
  const int NUM_COLS = 2;
  int milesTracker[NUM_ROWS][NUM_COLS]  { 3, -4, 42, 7 };

  // http://www.cplusplus.com/reference/algorithm/minmax_element/
  auto mm = std::minmax_element( milesTracker[0], milesTracker[0] + NUM_ROWS * NUM_COLS );
  std::cout << "min " << *mm.first << "\tmax " << *mm.second << '\n';
}
Topic archived. No new replies allowed.