Monday, October 7, 2024
Google search engine
HomeData Modelling & AIJava Program to Interchange elements of first and last rows in matrix

Java Program to Interchange elements of first and last rows in matrix

Given a 4 x 4 matrix, we have to interchange the elements of first and last row and show the resulting matrix.
Examples : 
 

Input : 3 4 5 0
        2 6 1 2
        2 7 1 2
        2 1 1 2
Output : 2 1 1 2
         2 6 1 2
         2 7 1 2
         3 4 5 0

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

 

The approach is very simple, we can simply swap the elements of first and last row of the matrix inorder to get the desired matrix as output.
Below is the implementation of the approach : 
 

Java




// Java code to swap the element of first
// and last row and display the result
import java.io.*;
 
public class Interchange {
     
    static void interchangeFirstLast(int m[][])
    {
        int rows = m.length;
         
        // swapping of element between first
        // and last rows
        for (int i = 0; i < m[0].length; i++) {
            int t = m[0][i];
            m[0][i] = m[rows-1][i];
            m[rows-1][i] = t;
        }
    }
     
    // Driver code
    public static void main(String args[]) throws IOException
    {
        // input in the array
        int m[][] = { { 8, 9, 7, 6 },
                    { 4, 7, 6, 5 },
                    { 3, 2, 1, 8 },
                    { 9, 9, 7, 7 } };
                     
        interchangeFirstLast(m);
         
        // printing the interchanged matrix
        for (int i = 0; i < m.length; i++) {
            for (int j = 0; j < m[0].length; j++)
                System.out.print(m[i][j] + " ");
            System.out.println();
        }
    }
}


Output : 
 

9 9 7 7 
4 7 6 5 
3 2 1 8 
8 9 7 6 

Time Complexity: O(N*M), as printing the matrix takes O(N*M) time where N and M are dimensions of the matrix.

Auxiliary Space: O(1), as we are not using any extra space.

Please refer complete article on Interchange elements of first and last rows in matrix for more details!

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Last Updated :
19 Jul, 2022
Like Article
Save Article


Previous

<!–

8 Min Read | Java

–>


Next


<!–

8 Min Read | Java

–>

RELATED ARTICLES

Most Popular

Recent Comments