C Online Compiler
Example: Interchange Two Columns in a Matrix in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Interchange Two Columns in a Matrix #include <stdio.h> #define ROWS 3 #define COLS 3 // Function to print the matrix void printMatrix(int matrix[ROWS][COLS]) { for (int i = 0; i < ROWS; i++) { for (int j = 0; j < COLS; j++) { printf("%d ", matrix[i][j]); } printf("\n"); } } int main() { // Step 1: Initialize the matrix int matrix[ROWS][COLS] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int col1, col2; // Columns to interchange int temp; // Temporary variable for swapping printf("Original Matrix:\n"); printMatrix(matrix); // Step 2: Get user input for columns to swap printf("Enter the first column to interchange (0 to %d): ", COLS - 1); scanf("%d", &col1); printf("Enter the second column to interchange (0 to %d): ", COLS - 1); scanf("%d", &col2); // Validate input columns if (col1 < 0 || col1 >= COLS || col2 < 0 || col2 >= COLS) { printf("Invalid column numbers. Please enter values between 0 and %d.\n", COLS - 1); return 1; } // Step 3: Interchange the elements of the specified columns for (int i = 0; i < ROWS; i++) { temp = matrix[i][col1]; matrix[i][col1] = matrix[i][col2]; matrix[i][col2] = temp; } printf("\nMatrix after interchanging Column %d and Column %d:\n", col1, col2); printMatrix(matrix); return 0; }
Output
Clear
ADVERTISEMENTS