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
#include <stdio.h>
#define n 3
void interchangeFirstLast( int m[][n])
{
int rows = n;
for ( int i = 0; i < n; i++)
{
int t = m[0][i];
m[0][i] = m[rows - 1][i];
m[rows - 1][i] = t;
}
}
int main()
{
int m[n][n] = {{6, 3, 1},
{4, 5, 2},
{2, 4, 9}};
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" );
}
interchangeFirstLast(m);
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!
Last Updated :
19 Jul, 2022
Like Article
Save Article