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, MatrixAlgorithm:
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
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
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
- Array and Matrix programming exercises index.
- C program to find sum of main diagonal elements of a matrix.
- C program to find sum of opposite diagonal elements of a matrix.
- C program to find lower triangular matrix.
- C program to find upper triangular matrix.
- C program to find transpose of a matrix.
- C program to find determinant of a matrix.
- C program to calculate sum of digits of a number.
- C program to check whether a number is palindrome or not.
- C program to find sum of first and last digit of any number.
- C program to create Simple calculator using switch case.
- C program to find maximum and minimum elements in array.
- C program to count total number of negative elements in an array.
- C program to find second largest element in an array.