Initializing diagonal of 2d array?

I have an array that only shows the bottom left, and most of the diagonal is blocked out. It looks something like this:

0****
1****
12***
385**
4679*

I'm trying to mirror the 2d array above the diagonal, while making it so the diagonal numbers are equal to the biggest number within their row (for example, the diagonal number for row 1 would be 1.

The output would be something like:

01134
11286
12257
38589
46799

I have an idea of the code for mirroring already:

1
2
3
4
5
6
7
  for(i = 0; i < arraySize; i++) { //rows
    for (j = i+1; j < arraySize; j++) { //columns
        int temp = array[i][j]; //temp array storing original
        array[i][j] = array[j][i]; //mirror the array
        array[j][i] = temp; //new array stored
    }
}


I don't know where to go from here to initialize each diagonal of the array. I just know that each diagonal can be found using the statement if(i==j) or possibly if (array[i][i] % 2 = 0). I'm stuck, and I can't use STL functions.
Last edited on
There is no need for a temporary variable since you aren't changing anything below the main diagonal. (Just drop lines 3 and 5).

Could you clarify exactly what you are trying to do on the diagonal? The biggest number in row 1*286 is 8, not 1. Did you mean the biggest number TO THE LEFT OF the diagonal?

Once you have clarified what you are going to do on the diagonal you can have a second loop to find the diagonal elements
1
2
3
4
5
  for(i = 0; i < arraySize; i++)
  {
      // some loop over j, depending on what you really want to do on the diagonal
      array[i][i] =  //whatever you come up with after your loop over j 
   }


Last edited on

The biggest number in row 1*286 is 8, not 1. Did you mean the biggest number TO THE LEFT OF the diagonal?


Yes, that's what I meant. I'm stuck.
OK, here's an outline.

- Declare your initial matrix array[][] and put values in it; (you can either put 0 in place of * for now, or simply leave those elements not set.

- You have already set up the correct loop structure for "mirroring" - setting values above the main diagonal, but you can (actually, must) remove your lines with variable 'temp' in. Note that j ranges from i+1 to the end, i.e. to the right of the diagonal. You have that correct here.

- Then to set the remaining diagonal elements you can have a second nested loop, but j will range over values less than the outer-loop (row) counter i, because you are finding the maximum value to the left of the diagonal. After the inner j loop has run you can set the diagonal element a[i][i] for this row, as in my sample.

Have a go at coding this.

If you are going to use this a lot then consider putting the matrix transformation in a function. However, get it working first.


Topic archived. No new replies allowed.