Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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 <stdio.h>
 
#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)



Last Updated : 19 Jul, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads