C Program to Interchange Elements of First and Last in a Matrix Across Columns
Here, we will see how to interchange the elements of the first and last element/entries in a matrix across columns; with an approach of swapping.
Input:
9 7 5 2 3 4 5 2 6
Output:
5 7 9 4 3 2 6 2 5
Approach: Swapping
The approach is very simple for this program, we can simply swap the elements of the first and last columns of the matrix in order to get the desired matrix as output.
Example:
C
// C program to swap the element of first and last column of // the matrix and display the result #include <stdio.h> #define n 3 // macros void interchangeFirstLast( int mat[][n]) { // swap the elements between first and last columns for ( int i = 0; i < n; i++) { int t = mat[i][0]; mat[i][0] = mat[i][n - 1]; mat[i][n - 1] = t; } } // Driver code int main() { // input matrix int mat[n][n] = { { 2, 4, 6 }, { 8, 2, 3 }, { 1, 9, 4 } }; // print input matrix printf ( "Input Matrix: \n" ); for ( int i = 0; i < n; i++) { for ( int j = 0; j < n; j++) { printf ( "%d " , mat[i][j]); } printf ( "\n" ); } // call interchangeFirstLast(mat) function. // This function swap the element of first and last // columns. interchangeFirstLast(mat); // print output matrix printf ( "Output Matrix: \n" ); for ( int i = 0; i < n; i++) { for ( int j = 0; j < n; j++) { printf ( "%d " , mat[i][j]); } printf ( "\n" ); } } |
Output
Input Matrix: 2 4 6 8 2 3 1 9 4 Output Matrix: 6 4 2 3 2 8 4 9 1
Time Complexity: O(n)
Auxiliary Space: O(1)
Contact Us