Search code examples
cmatrixrandomcycle

How to print main diagonal of matrix and how to fill matrix with random numbers


I have matrix a[i][j] for example i = j = d (for example 3) . How can I fill it with random numbers and then I need to show main diagonal and another diagonal over and below matrix. Almost all examples that I found were for c++ but I need to do it in C.

I thought about cycle but I don't know how to use it. According to my idea it should take point a[0][0] and i = 0, i++ , i < d and j=0, j++ ,j < d. This will be main diagonal. And another one is i = d , i--, j=0 , j++ . Therefore it will take both diagonals and then print it though 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

Solution

  • 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