Array-promo
Matrix-promo

Question

Write a program in java to take size of 2D integer array(that is, number of rows and number of columns) and integer elements in the array from the user. Swap first row with last row without using another array. Display the array  and array after swapping.

				
					OUTPUT:
Enter Number of rows:
4
Enter Number of columns:
4
Enter Elements in Array:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Original Array:
1 2 3 4 
5 6 7 8 
9 10 11 12 
13 14 15 16 
Array after swapping first and last row:
13 14 15 16 
5 6 7 8 
9 10 11 12 
1 2 3 4 
				
			

Share code with your friends

Share on whatsapp
Share on facebook
Share on twitter
Share on telegram

Code

				
					import java.util.Scanner;
public class SwapFirstAndLastRow
{
    public static void main()
    {
        int[ ][ ] arr;
        int row,col;
        int i,j,k,temp=0;
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter Number of rows:");
        row=sc.nextInt();
        System.out.println("Enter Number of columns:");
        col=sc.nextInt();
        arr=new int[row][col];
        System.out.println("Enter Elements in Array:");
        for(i=0;i< row;i++)
        {
            for(j=0;j< col;j++)
            {
                arr[i][j]=sc.nextInt();
            }
        }
        System.out.println("Original Array:");
        for(i=0;i< row;i++)
        {
            for(j=0;j< col;j++)
            {
                System.out.print(arr[i][j]+" ");
            }
            System.out.println();
        }
        k=row-1;
        i=0;
        for(j=0;j< col;j++)
        {
            temp=arr[i][j];
            arr[i][j]=arr[k][j];
            arr[k][j]=temp;           
        }
        System.out.println("Array after swapping first and last row:");
        for(i=0;i< row;i++)
        {
            for(j=0;j< col;j++)
            {
                System.out.print(arr[i][j]+" ");
            }
            System.out.println();
        }
    }
}


				
			

Coding Store

Leave a Reply

Your email address will not be published. Required fields are marked *