C program to interchange diagonals of a matrix

Write a C program to read elements in a matrix and interchange elements of primary(major) diagonal with secondary(minor) diagonal. C program for interchanging diagonals of a matrix.

Example: If elements of matrix are:
1 2 3
4 5 6
7 8 9

Matrix after interchanging its diagonal:
3 2 1
4 5 6
9 8 7

Required knowledge:

Basic C programming, For loop, Array, Matrix

Algorithm:

Interchanging diagonal of a matrix

Logic to interchange diagonals of matrix A:
Step 1: temp = A[row][col]
Step 2: A[row][col] = A[row][ (N-col)-1 ] (Where N is the size of array).
Step 3: A[row][ (N-col)-1 ] = temp.

Program:

/**
 * C program to interchange diagonals of a matrix
 */
 
#include <stdio.h>
#define MAX_ROWS 3
#define MAX_COLS 5

int main()
{
    int A[MAX_ROWS][MAX_COLS];
    int row, col, square, temp;
 
    /*
     * Reads elements in matrix from user
     */
    printf("Enter elements in matrix of size %dx%d: \n", MAX_ROWS, MAX_COLS);
    for(row=0; row < MAX_ROWS; row++)
    {
        for(col=0; col < MAX_COLS; col++)
        {
            scanf("%d", &A[row][col]);
        }
    }

    square = (MAX_ROWS < MAX_COLS) ? MAX_ROWS : MAX_COLS;
 
    /*
     * Interchanges diagonal of the matrix
     */
    for(row=0; row < square; row++)
    {
        col = row;
 
        temp = A[row][col];
        A[row][col] = A[row][(square - col)-1];
        A[row][(square - col)-1] = temp;
    }
 
    /*
     * Prints the interchanged diagonals matrix
     */
    printf("\nMatrix after diagonals interchanged: \n");
    for(row=0; row < MAX_ROWS; row++)
    {
        for(col=0; col < MAX_COLS; col++)
        {
            printf("%d ", A[row][col]);
        }
 
        printf("\n");
    }
 
    return 0;
}
Output
X
_
Enter elements in matrix of size 3x3:
1 2 3
4 5 6
7 8 9

Matrix after diagonals interchanged:
3 2 1
4 5 6
9 8 7

Happy coding ;)


You may also like

Labels: , , ,