Newbie992 wrote: |
---|
Can you explain what does this line do? |
In this instance, since i and o have minimum values 0, the line is equivalent to
if ( i == 0 && o == 0 ) maximum = x[0][0];
As @Repeater pointed out very early on, you can't set the maximum to x[0][0] until x[0][0] has itself been initialised and that line allows it to be done exactly when necessary and when possible ... IF you choose to do it within the loop.
However, finding a maximum is a separate thing, and I'm inclined to think it would be better to do it AFTER all the data has been input. (Indeed, there's a good argument for doing it in a separate function.)
The following code shows you two ways of getting the maximum after all input: from first principles using nested loops, the second using a standard-library routine (you can look it up). Since arrays like this use contiguous storage (i.e. all elements one after another) you can also do what @jonnin suggested and fake a 1-d array with MAXI*MAXJ elements, so avoiding nesting loops: this is actually what the max_element routine is doing.
Note that I have done a couple of things that make the code a bit easier on the eyes:
- changed variable o (easily confused with 0) to j;
- avoided slightly arbitrary numbers like 4 and 5 and named them as MAXI and MAXJ; then if you want to change them you need only do so in one place. (I've also made them a bit smaller so as to shorten the input during testing).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
const int MAXI = 3, MAXJ = 3; // try not to use "magic numbers": fix them just once
int x[MAXI][MAXJ];
// Enter numbers
for ( int i = 0; i < MAXI; i++ )
{
for ( int j = 0; j < MAXJ; j++)
{
cout << "Enter element [" << i << "][" << j << "]: ";
cin >> x[i][j];
}
}
// Find maximum
int maximum = x[0][0]; // initialise to first element
for ( int i = 0; i < MAXI; i++ )
{
for ( int j = 0; j < MAXJ; j++)
{
if ( x[i][j] > maximum ) maximum = x[i][j];
}
}
cout << "Maximum number is " << maximum << endl;
// Find maximum (alternative method)
int *p = &x[0][0];
cout << "Maximum number is " << *max_element( p, p + MAXI * MAXJ ) << endl;
}
|