Square matrix exercise
Feb 27, 2015 at 3:55pm UTC
The exercise is:
Manage a square matrix of order N by:
- Determining and storing the maximum of each line;
- Determining and storing the minimum of each column;
- Calculate the difference between the relative maximum and minimum of the same location;
- Print a table showing the maximum, minimum, and their differences.
I was able to do the first two point and I'd like you to check if it's alright.
This is my code:
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 42 43 44 45 46
#include <iostream>
using namespace std;
int main () {
//Initialization:
const int N = 10;
const int M = 20;
int mat[N][N];
int vecmax[M] = {0};
int vecmin[M] = {0};
int n = 3;
mat [0][0] = 1; mat [0][1] = 4; mat [0][2] = -1;
mat [1][0] = 6; mat [1][1] = 6; mat [1][2] = 5;
mat [2][0] = -2; mat [2][1] = 7; mat [2][2] = 10;
//Procedure:
for (int i = 0; i<n; i++) {
for (int j = 0; j<n; j++) {
if (mat[i][j] > vecmax[i]) {
vecmax[i] = mat[i][j];
}
}
}
for (int i = 0; i<n; i++) {
vecmin[i] = mat[i][i];
for (int j = 0; j<n; j++) {
if (mat[j][i] < vecmin[i]) {
vecmin[i] = mat[j][i];
}
}
}
//Output:
for (int i = 0; i<n; i++) {
cout<<vecmax[i]<<" " ;
}
cout<<"\n" ;
for (int i = 0; i<n; i++) {
cout<<vecmin[i]<<" " ;
}
//Termination:
return 0;
}
In the third point I should find the position of each max and min number. How do I do that?
Feb 27, 2015 at 5:33pm UTC
Don't just store the min/max itself, also store the position you found it.
Feb 28, 2015 at 9:58am UTC
How? Should I create two arrays of position?
Feb 28, 2015 at 10:19am UTC
Let X = maximum of each line
Let Y = minimum of each column
Then
Calculate the difference between the relative maximum and minimum of the same location;
For each index in the matrix M(i,j), Difference = X(i) - Y(j).
Then print the table of X(i) | Y(j) | Difference
Feb 28, 2015 at 4:18pm UTC
What do you mean by
For each index in the matrix M(i,j), Difference = X(i) - Y(j).
? I don't understand it. The way you wrote it would be like:
1 2 3 4 5
for (int i = 0; i<n; i++) {
for (int j = 0; j<n; j++) {
difference = X(i) - Y(j);
}
}
And it simply do the difference without taking into account "the same location".
Topic archived. No new replies allowed.