C Online Compiler
Example: Interchange Two Rows in a Matrix in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Interchange Two Rows 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 row1, row2; // Rows to interchange int temp; // Temporary variable for swapping printf("Original Matrix:\n"); printMatrix(matrix); // Step 2: Get user input for rows to swap printf("Enter the first row to interchange (0 to %d): ", ROWS - 1); scanf("%d", &row1); printf("Enter the second row to interchange (0 to %d): ", ROWS - 1); scanf("%d", &row2); // Validate input rows if (row1 < 0 || row1 >= ROWS || row2 < 0 || row2 >= ROWS) { printf("Invalid row numbers. Please enter values between 0 and %d.\n", ROWS - 1); return 1; } // Step 3: Interchange the elements of the specified rows for (int j = 0; j < COLS; j++) { temp = matrix[row1][j]; matrix[row1][j] = matrix[row2][j]; matrix[row2][j] = temp; } printf("\nMatrix after interchanging Row %d and Row %d:\n", row1, row2); printMatrix(matrix); return 0; }
Output
Clear
ADVERTISEMENTS