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. Logic to interchange diagonals of a matrix in C programming.

Example

Input

Input matrix elements: 
1 2 3
4 5 6
7 8 9

Output

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

Required knowledge

Basic C programming,For loop, Array

Read more -

Matrix diagonal interchanged

Program to interchange diagonal elements of a matrix

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

int main()
{
    int A[MAX_ROWS][MAX_COLS];
    int row, col, size, temp;
 
    /* Input 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]);
        }
    }

    size = (MAX_ROWS < MAX_COLS) ? MAX_ROWS : MAX_COLS;
 
    /*
     * Interchange diagonal of the matrix
     */
    for(row=0; row<size; row++)
    {
        col = row;
 
        temp = A[row][col];
        A[row][col] = A[row][(size-col) - 1];
        A[row][(size-col) - 1] = temp;
    }
 
    /*
     * Print 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

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 😉

About Pankaj

Pankaj Prakash is the founder, editor and blogger at Codeforwin. He loves to learn new techs and write programming articles especially for beginners. He works at Vasudhaika Software Sols. as a Software Design Engineer and manages Codeforwin. In short Pankaj is Web developer, Blogger, Learner, Tech and Music lover.

Follow on: Facebook | Twitter | Google | or

Comments and discussion
Have a doubt, write here. I will help my best.
Before commenting you must escape your source code before commenting. Paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>