# C Program to Interchange Elements of First and Last in a Matrix Across Rows

Here, we will see how to interchange the elements of first and last in a matrix across rows. Below are the examples:

Input: 6 3 1
4 5 2
2 4 9
Output: 2 4 9
4 5 2
6 3 1

Input: 1 3 5
4 5 2
2 2 4
Output: 2 2 4
4 5 2
1 3 5

Approach: The approach is very simple, swap the elements of the first and last row of the matrix in order to get the desired matrix as output.

Below is the C program to interchange the elements of first and last in a matrix across rows:

## C

 `// C program interchange the elements ` `// of first and last in a matrix ` `// across rows.` `#include `   `#define n 3`   `// Function to swap the element ` `// of first and last row` `void` `interchangeFirstLast(``int` `m[][n])` `{` `    ``int` `rows = n;`   `    ``// Swapping of element between first` `    ``// and last rows` `    ``for` `(``int` `i = 0; i < n; i++) ` `    ``{` `        ``int` `t = m[0][i];` `        ``m[0][i] = m[rows - 1][i];` `        ``m[rows - 1][i] = t;` `    ``}` `}`   `// Driver code` `int` `main()` `{` `    ``// Input matrix` `    ``int` `m[n][n] = {{6, 3, 1}, ` `                   ``{4, 5, 2}, ` `                   ``{2, 4, 9}};`   `    ``// Printing the input matrix` `    ``printf``(``"Input Matrix: \n"``);` `    ``for` `(``int` `i = 0; i < n; i++) ` `    ``{` `        ``for` `(``int` `j = 0; j < n; j++) ` `        ``{` `            ``printf``(``"%d "``, m[i][j]);` `        ``}` `        ``printf``(``"\n"``);` `    ``}`   `    ``// call interchangeFirstLast(m) function.` `    ``// This function swap the element of ` `    ``// first and last row` `    ``interchangeFirstLast(m);`   `    ``// Printing the original matrix` `    ``printf``(``"\nOutput Matrix: \n"``);` `    ``for` `(``int` `i = 0; i < n; i++) ` `    ``{` `        ``for` `(``int` `j = 0; j < n; j++) ` `        ``{` `            ``printf``(``"%d "``, m[i][j]);` `        ``}` `        ``printf``(``"\n"``);` `    ``}` `}`

Output

```Input Matrix:
6 3 1
4 5 2
2 4 9

Output Matrix:
2 4 9
4 5 2
6 3 1 ```

Time Complexity: O(n2)
Auxiliary Space: O(1)

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Previous
Next