In this article, we will write a C program to interchange two random rows in a matrix. Below are the inputs that will be taken from the user:
- The number of rows & columns in the matrix
- The elements in the matrix
- The rows that will be interchanged
Examples:
Input:
rows = 3, columns = 3
arr[i, j] = {{2, 1, 3}
{1, 2, 6}
{3, 8, 1}}
r1 = 2, r2 = 3
Output:
arr[i, j] = {{2, 1, 3}
{3, 8, 1}
{1, 2, 6}}
Input:
rows = 3, columns = 3
arr[i, j] = {{1, 2, 3}
{4, 5, 6}
{7, 8, 9}}
r1 = 1, r2 = 2
Output:
arr[i, j] = {{4, 5, 6}
{1, 2, 3}
{7, 8, 9}}
Approach: A simple & straightforward approach is to iterate through the matrix to reach the target rows and then swap the elements in both rows to get the desired matrix as output.
Example:
// C program to interchange two random rows in a matrix
#include <stdio.h>
int main()
{
int rows, columns;
printf("Enter the number of rows & columns: ");
scanf("%d %d", &rows, &columns);
int i, j, arr[10][10];
printf("\nEnter the elements:\n\n");
for (i = 0; i < rows; ++i) {
for (j = 0; j < columns; ++j) {
printf("Matrix[%d][%d]: ", i, j);
scanf("%d", &arr[i][j]);
}
}
printf("\nMatrix before interchanging rows:\n");
for (i = 0; i < rows; ++i) {
for (j = 0; j < columns; ++j) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
int r1, r2, temp;
printf("\nEnter two row numbers that will be "
"interchanged: ");
scanf("%d %d", &r1, &r2);
// Swap elements in both rows
for (i = 0; i < rows; ++i) {
temp = arr[r1 - 1][i];
arr[r1 - 1][i] = arr[r2 - 1][i];
arr[r2 - 1][i] = temp;
}
printf("\nMatrix after interchanging rows:\n");
for (i = 0; i < rows; ++i) {
for (j = 0; j < columns; ++j) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
return 0;
}
Output:
Enter the number of rows & columns: 3 3 Enter the elements: Matrix[0][0]: 1 Matrix[0][1]: 2 Matrix[0][2]: 4 Matrix[1][0]: 5 Matrix[1][1]: 8 Matrix[1][2]: 9 Matrix[2][0]: 4 Matrix[2][1]: 2 Matrix[2][2]: 6 Matrix before interchanging rows: 1 2 4 5 8 9 4 2 6 Enter two row numbers that will be interchanged: 2 3 Matrix after interchanging rows: 1 2 4 4 2 6 5 8 9