PAPAmidNIHGT - 11 months ago 53

C Question

I have matrix

`a[i][j]`

`i = j = d`

`3`

I thought about

`cycle`

`a[0][0]`

`i = 0`

`i++`

`i < d`

`j=0`

`j++`

`j < d`

`i = d`

`i--`

`j=0`

`j++`

`printf`

It should look like this

`1 6 11 16 - main diagonal`

13 10 7 4 - additional diagonal

`1 2 3 4`

5 6 7 8

9 10 11 12 - random matrix

13 14 15 16

`1 6 11 16 - main diagonal`

13 10 7 4 - additional diagonal

Answer Source

Here is a version that populates a square matrix with random numbers, and then stores the primary and secondary diagonals in two arrays. These two arrays are filled at the same time in a single loop. Then the program displays the contents of each of the three arrays.

```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
size_t d = 4;
int a[d][d];
int primary[d], secondary[d];
size_t i, j;
srand(time(NULL));
/* Fill array with random numbers */
for (i = 0; i < d; i++)
for (j = 0; j < d; j++)
a[i][j] = rand() % 100;
/* Store diagonals */
for (i = 0; i < d; i++) {
primary[i] = a[i][i];
secondary[i] = a[d - (i + 1)][i];
}
/* Display arrays */
puts("2d Array:");
for (i = 0; i < d; i++) {
for (j = 0; j < d; j++) {
printf("%-5d", a[i][j]);
}
putchar('\n');
}
putchar('\n');
puts("Primary Diagonal:");
for (i = 0; i < d; i++)
printf("%-5d", primary[i]);
printf("\n\n");
puts("Secondary Diagonal:");
for (i = 0; i < d; i++)
printf("%-5d", secondary[i]);
printf("\n\n");
return 0;
}
```

Here is a sample run:

```
2d Array:
65 59 91 10
17 25 19 44
94 77 68 21
91 76 18 19
Primary Diagonal:
65 25 68 19
Secondary Diagonal:
91 77 19 10
```