The Wayback Machine - https://web.archive.org/web/20241123074619/https://www.geeksforgeeks.org/java-program-to-interchange-elements-of-first-and-last-in-a-matrix-across-rows/
Open In App

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

Last Updated : 27 Sep, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

For a given 4 × 4 matrix, the task is to interchange the elements of the first and last rows and then return the resultant matrix.

Illustration:

Input 1:  1  1  5  0
          2  3  7  2
          8  9  1  3
          6  7  8  2
Output 1: 6  7  8  2
          2  3  7  2 
          8  9  1  3
          1  1  5  0

Input 2:  7   8   9  10
         11  13  14   1
         15   7  12  22
         11  21  30   1

Output 2: 11  21  30   1
         11  13  14   1
         15  7   12  22
         7   8   9   10

Approach:

To get the required output, we need to swap the elements of the first and the last row of the stated matrix.

Example

Java




// Java Program to Interchange Elements of First
// and Last Row in a Matrix
 
// Importing input output classes
import java.io.*;
 
// Main Class
public class GFG {
 
    // Method 1
    // To swap First and Last Row
    static void swap_First_last(int mat[][])
    {
        int rws = mat.length;
 
        // Interchanging of elements between the
        // first and last rows
        for (int j = 0; j < mat[0].length; j++) {
 
            // Using temporary variable so in order
            // not to lose the values of the matrix
            // Simply, swapping the values stored
            int temp = mat[0][j];
            mat[0][j] = mat[rws - 1][j];
            mat[rws - 1][j] = temp;
        }
    }
 
    // Method 2
    // Main driver method
    public static void main(String args[])
        throws IOException
    {
        // Input integer matrix
        int mat[][] = { { 2, 3, 4, 5 },
                        { 8, 9, 6, 15 },
                        { 13, 22, 11, 18 },
                        { 19, 1, 2, 0 } };
 
        // Display message only
        System.out.println("Input matrix is as follows : ");
 
        // Printing the Input matrix
        for (int j = 0; j < mat.length; j++) {
            for (int k = 0; k < mat[0].length; k++)
 
                // Print the elements of the input matrix
                System.out.print(mat[j][k] + " ");
 
            // New line as row ended
            System.out.println();
        }
 
        System.out.println(
            "Swapped matrix is as follows : ");
 
        // Calling the (method1) to swap rows in a matrix
        swap_First_last(mat);
 
        // Printing the Swapped matrix
        for (int j = 0; j < mat.length; j++) {
            for (int k = 0; k < mat[0].length; k++)
 
                // Print the elements of the swapped matrix
                System.out.print(mat[j][k] + " ");
 
            // New line as row ended
            System.out.println();
        }
    }
}


Output:

Input matrix is as follows : 
2 3 4 5 
8 9 6 15 
13 22 11 18 
19 1 2 0 
Swapped matrix is as follows : 
19 1 2 0 
8 9 6 15 
13 22 11 18 
2 3 4 5

Time Complexity: O(n*m) where n and m are numbers of rows and columns respectively.
Auxiliary Space: O(1)



Previous Article
Next Article

Similar Reads

Java Program to Interchange Elements of First and Last in a Matrix Across Columns
For a given 4 x 4 matrix, the task is to interchange the elements of the first and last columns and then return the resultant matrix. Example Test Case for the ProblemInput : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16Output : 4 2 3 1 8 6 7 5 12 10 11 9 16 14 15 13 Implementation of Interchange Elements of First and Last in a Matrix Across Columns[GFGTA
2 min read
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 fir
2 min read
Java Program to Interchange Any Two Rows in the Matrix
Given a matrix having m rows and n columns. We have to write a Java program to interchange any two Rows in the given matrix. Swap Operation is required to interchange the elements of two rows. O(1) operation to swap two rows is impossible because complete traversal between two rows is required. Examples Input 1: K = 1, L = 2, mat[][] = {{2, 1, 4},
2 min read
Java Program to Sort the 2D Array Across Rows
This program is used to Sort the 2D array Across rows. We will use the concept of vector to sort each row. Vector Vector(): Creates a default vector of the initial capacity is 10. Vector<E> v = new Vector<E>(); Functions we will use in this: 1. removeAll(): The java.util.vector.removeAll(Collection col) method is used to remove all the
3 min read
Java Program to Interchange Any Two Columns in the Matrix
Given a matrix having m rows and n columns. We have to write a Java program to interchange any two Columns(ie column no K and L given in the input) in the given matrix. Swap Operation is required to interchange the elements of two columns. O(1) operation to swap two columns is impossible because complete traversal between two columns is required. E
2 min read
Java Program to Accept a Matrix of Order M x N & Interchange the Diagonals
Problem Description: Write a Java program that accepts a matrix of M × N order and then interchange diagonals of the matrix. Steps: 1. We can only interchange diagonals for a square matrix. 2. Create a square matrix of size [M × M]. 3. Check the matrix is a square matrix or not. If the matrix is square then follow step 3 else terminate the program.
4 min read
Java Program to Interchange Diagonals of Matrix
Given a square matrix of order n*n, you have to interchange the elements of both diagonals. Examples : Input : matrix[][] = {1, 2, 3, 4, 5, 6, 7, 8, 9} Output : matrix[][] = {3, 2, 1, 4, 5, 6, 9, 8, 7} Input : matrix[][] = {4, 2, 3, 1, 5, 7, 6, 8, 9, 11, 10, 12, 16, 14, 15, 13} Output : matrix[][] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 11, 14, 1
2 min read
Java Program for Mirror of matrix across diagonal
Given a 2-D array of order N x N, print a matrix that is the mirror of the given tree across the diagonal. We need to print the result in a way: swap the values of the triangle above the diagonal with the values of the triangle below it like a mirror image swap. Print the 2-D array obtained in a matrix layout. Examples: Input : int mat[][] = {{1 2
4 min read
Java Program to Use Color Interchange Method to Perform Vertex Coloring of Graph
Graph Coloring is the method to assign colors to certain elements of a graph. The most common method for this is the Vertex Coloring Method. We will be given m colors, we will apply each color to the vertex. We use here the “Backtracking” Algorithm. Illustration: Input: V = 4, C = 2 Here V denotes colour and C denotes color Graph: { { 0, 1, 0, 0, 0
5 min read
Java Program to Sort 2D Array Across Columns
The Vector class implements a growable array of objects. Vectors basically fall in legacy classes but now it is fully compatible with collections. It is found in the java.util package and implements the List interface, so we can use all the methods of List interface here. This program is used to Sort the 2D array Across Columns. We will use the con
3 min read
Java Program to Sort 2D Array Across Left Diagonal
The Vector class implements a growable array of objects. Vectors basically fall in legacy classes but now it is fully compatible with collections. It is found in java.util package and implements the List interface, so we can use all the methods of List interface here. This program is used to Sort the 2D array Across Left Diagonal. We will use the c
3 min read
Java Program to Get First or Last Elements from HashSet
The HashSet class implements the Set interface, backed by a hash table which is actually a HashMap instance. There is no guarantee made for the iteration order of the set which means that the class does not guarantee the constant order of elements over time. This class permits the null element. The class also offers constant time performance for th
3 min read
Get first and last elements from ArrayList in Java
Given an array list, find the first and last elements of it. Examples: Input : aList = {10, 30, 20, 14, 2} Output : First = 10, Last = 2 Input : aList = {10, 30, 40, 50, 60} Output : First = 10, Last = 60 The last element is at index, size - 1 and the first element is stored at index 0. If we know how to get the size of ArrayList then we can get th
3 min read
Remove First and Last Elements from LinkedList in Java
The Java.util.LinkedList.removeFirst() method is used to remove the first element from the LinkedList. The Java.util.LinkedList.removeLast() method is used to remove the last element from the LinkedList. Both the methods also returns the element after removing it. 1. removeFirst() Syntax: LinkedList.removeFirst() Parameters: This function does not
2 min read
Java program to swap first and last characters of words in a sentence
Write a Java Program to Swap first and last character of words in a Sentence as mentioned in the example? Examples: Input : geeks for geeks Output :seekg rof seekg Approach:As mentioned in the example we have to replace first and last character of word and keep rest of the alphabets as it is. First we will create an Char array of given String by us
2 min read
Java Program to Get the First and the Last Element of a Linked List
A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The given task is to retrieve the first and the last element of a given linked list. Properties of a Linked ListElements are stored in a non-contiguous manner.Every element is an object which contains a pointer to the next element.Example
4 min read
Java Program to Maximize sum of diagonal of a matrix by rotating all rows or all columns
Given a square matrix, mat[][] of dimensions N * N, the task is find the maximum sum of diagonal elements possible from the given matrix by rotating either all the rows or all the columns of the matrix by a positive integer. Examples: Input: mat[][] = { { 1, 1, 2 }, { 2, 1, 2 }, { 1, 2, 2 } }Output: 6 Explanation: Rotating all the columns of matrix
3 min read
Java Program to Check if all rows of a matrix are circular rotations of each other
Given a matrix of n*n size, the task is to find whether all rows are circular rotations of each other or not. Examples: Input: mat[][] = 1, 2, 3 3, 1, 2 2, 3, 1Output: Yes, All rows are rotated permutation of each other.Input: mat[3][3] = 1, 2, 3 3, 2, 1 1, 3, 2Output: No, Explanation : As 3, 2, 1 is not a rotated or circular permutation of 1, 2, 3
3 min read
Find first and last element of ArrayList in java
Prerequisite: ArrayList in Java Given an ArrayList, the task is to get the first and last element of the ArrayList in Java, Examples: Input: ArrayList = [1, 2, 3, 4] Output: First = 1, Last = 4 Input: ArrayList = [12, 23, 34, 45, 57, 67, 89] Output: First = 12, Last = 89 Approach: Get the ArrayList with elements.Get the first element of ArrayList w
2 min read
How to Add Element at First and Last Position of LinkedList in Java?
LinkedList is a part of Collection framework present inside java.util package. This class is an implementation of LinkedList data structure which is a linear data structure where the elements are not stored in a contiguous manner and every element is a separate object with a data field and address field. Now here we are given a Linked List, the tas
2 min read
How to find the first and last character of a string in Java
Given a string str, the task is to print the first and the last character of the string. Examples: Input: str = "GeeksForGeeks" Output: First: G Last: s Explanation: The first character of the given string is 'G' and the last character of given string is 's'. Input: str = "Java" Output: First: J Last: a Explanation: The first character of given str
3 min read
How to Get First and Last Element From the Vector in Java?
The first element in the Vector can be obtained using the firstElement() method of vector class that is represent util package. The last element in the Vector can be obtained using the lastElement() method of vector class that is also represent util package. Neither of these methods requires any parameters. The first and last elements of the vector
2 min read
Swap the first and last character of a string in Java
Given string str, the task is to write a Java program to swap the first and the last character of the given string and print the modified string. Examples: Input: str = "GeeksForGeeks"Output: seeksForGeekGExplanation: The first character of the given string is 'G' and the last character of the given string is 's'. We swap the character 'G and 's' a
4 min read
Remove first and last character of a string in Java
Given string str, the task is to write Java Program to remove the first and the last character of the string and print the modified string. Examples: Input: str = "GeeksForGeeks"Output: eeksForGeekExplanation: The first character of the given string is 'G' and the last character of the given string is 's'. After removing the first and last characte
7 min read
How to Remove the First Entry or Last Entry from the Java TreeMap?
TreeMap is the implementation class of the Map interface. It allows the objects to be sorted according to the keys and sorting can be natural sorting or you can use a comparator. Insertion order is also not preserved in Tree Map. Syntax: TreeMap<String,Integer> map = new TreeMap<>();In the below example we will create one Tree Map and i
6 min read
How to Get First or Last Entry from Java LinkedHashMap?
LinkedHashMap is a predefined class in Java which is similar to HashMap, containing key and its respective value unlike HashMap, In LinkedHashMap insertion order is preserved. The task is to get the first and last entry present in LinkedHashMap. Iteration to get last and first value. The first and the last entry in Map is the entry that is inserted
5 min read
Java Program to Count of Array elements greater than all elements on its left and at least K elements on its right
Given an array A[ ] consisting of N distinct integers, the task is to find the number of elements which are strictly greater than all the elements preceding it and strictly greater than at least K elements on its right. Examples: Input: A[] = {2, 5, 1, 7, 3, 4, 0}, K = 3 Output: 2 Explanation: The only array elements satisfying the given conditions
7 min read
Check if the first and last digit of number N is prime and their sum is less than K
Given a number N, the task is to check if its first and last digit is a prime number and their sum is less than K, or not. If it is, then print Yes, else print No.Examples: Input: N = 322223, K = 10Output: Yes Input: N = 62531561, K = 15Output: No Approach: Check if the first and last digit of N is prime or not.If they are prime, then check if they
7 min read
Java Program to Determine if a given Matrix is a Sparse Matrix
A matrix is a collection of data elements arranged in a two-dimensional array-like structure, consisting of rows and columns. A matrix with a lot of zero values is called a sparse matrix. The program aims to count the number of zero values present in the matrix. If the number of zero values is more than half of the total number of elements in the m
3 min read
Java Program to Check Whether a Given Matrix is Lower Triangular Matrix or Not
In the lower triangular matrix, the elements that are present above the diagonal should be 0. Given a matrix and the task is to check the matrix is in lower triangular form or not. A matrix must be a square matrix. A square matrix is called lower triangular if all the entries above the main diagonal are zero. Example - Input: 1 0 0 1 2 0 1 2 3 Outp
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg