C Online Compiler
Example: Interchange Diagonals of a Matrix in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Interchange Diagonals of a Matrix #include <stdio.h> #define MAX_SIZE 10 // Define a maximum size for the matrix int main() { int matrix[MAX_SIZE][MAX_SIZE]; int m, n; // Variables for rows and columns // Step 1: Accept matrix dimensions from the user printf("Enter the number of rows (M): "); scanf("%d", &m); printf("Enter the number of columns (N): "); scanf("%d", &n); // Validate dimensions to ensure they fit within MAX_SIZE if (m <= 0 || n <= 0 || m > MAX_SIZE || n > MAX_SIZE) { printf("Invalid dimensions. M and N must be positive and less than or equal to %d.\n", MAX_SIZE); return 1; // Indicate an error } // Step 2: Check if the matrix is square (M == N) for diagonal interchange if (m != n) { printf("Diagonal interchange is typically defined for square matrices (M=N).\n"); printf("Cannot interchange diagonals for a non-square matrix of order %dx%d.\n", m, n); return 1; // Indicate an error or non-applicable scenario } // Step 3: Accept matrix elements from the user printf("Enter matrix elements:\n"); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { printf("Enter element [%d][%d]: ", i, j); scanf("%d", &matrix[i][j]); } } // Step 4: Display the original matrix printf("\nOriginal Matrix:\n"); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { printf("%d\t", matrix[i][j]); } printf("\n"); } // Step 5: Interchange the main and secondary diagonals // The main diagonal elements are at matrix[i][i] // The secondary diagonal elements are at matrix[i][m - 1 - i] for (int i = 0; i < m; i++) { int temp = matrix[i][i]; // Store main diagonal element matrix[i][i] = matrix[i][m - 1 - i]; // Replace with secondary diagonal element matrix[i][m - 1 - i] = temp; // Place stored main diagonal element into secondary position } // Step 6: Display the matrix after diagonal interchange printf("\nMatrix after interchanging diagonals:\n"); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { printf("%d\t", matrix[i][j]); } printf("\n"); } return 0; // Indicate successful execution }
Output
Clear
ADVERTISEMENTS