Program for ‘SWAP ROWS’

import java.util.Scanner;

public class Array_2D_SwapRows
{
public static int[][] swaprows(int[][] ar)
{
for (int i = 0; i < ar.length/2; i++)
{
for (int j = 0; j < ar[i].length; j++)
{
int temp = ar[i][j]; //swap the rows with the help of i and j value...
ar[i][j] = ar[ar.length-1-i][j];
ar[ar.length-1-i][j] = temp;
}
}
return ar;
}
 
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the Outer Array size : ");
int a = sc.nextInt();
System.out.println("Enter the Inner Array size : ");
int b = sc.nextInt();
 
int ar[][] = new int[a][b];
for (int i = 0; i < ar.length; i++) 
{
for (int j = 0; j < ar[i].length; j++) 
{
System.out.println("enter the value ar "+i+"th row and"+j+"the column");
ar[i][j] = sc.nextInt();
}
}
 
System.out.println("The array elements are :-");
for (int i = 0; i < ar.length; i++) 
{
for (int j = 0; j < ar[i].length; j++) 
{
System.out.print(ar[i][j]+" ");
}
System.out.println();
}
int nar[][] = swaprows(ar);
System.out.println("The array elements after SWAPPING :-");
for (int i = 0; i < nar.length; i++) 
{
for (int j = 0; j < nar[i].length; j++) 
{
System.out.print(nar[i][j]+" ");
}
System.out.println();
}
}
}

Output:-

Enter the Outer Array size :
3
Enter the Inner Array size :
3
enter the value ar 0th row and0the column
1
enter the value ar 0th row and1the column
2
enter the value ar 0th row and2the column
3
enter the value ar 1th row and0the column
4
enter the value ar 1th row and1the column
5
enter the value ar 1th row and2the column
6
enter the value ar 2th row and0the column
7
enter the value ar 2th row and1the column
8
enter the value ar 2th row and2the column
9
The array elements are :-
1 2 3
4 5 6
7 8 9
The array elements after SWAPPING :-
7 8 9
4 5 6
1 2 3