VOOZH about

URL: https://www.geeksforgeeks.org/c/c-program-to-interchange-two-random-rows-in-a-matrix/

⇱ C Program to Interchange Two Random Rows in a Matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

C Program to Interchange Two Random Rows in a Matrix

Last Updated : 1 Nov, 2022

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:

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
Comment