Dremendo Tag Line

Input numbers in 2d array and swap the largest with the smallest number in Java

Two Dimensional Array - Question 4

In this question, we will see how to input numbers in a 3X3 integer matrix (2d array) and interchange the largest with the smallest number from it in Java programming. To know more about two dimensional array click on the two dimensional array lesson.

Q4) Write a program in Java to input numbers in a 3X3 integer matrix (2d array) and interchange the largest with the smallest number from it.

Program

import java.util.Scanner;

public class Q4
{
    public static void main(String args[])
    {
        int a[][]=new int[3][3], r,c,lg=0,lr=0,lc=0,sm=0,srw=0,scl=0;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter 9 numbers");
        for(r=0; r<3; r++)
        {
            for(c=0; c<3; c++)
            {
                a[r][c]=sc.nextInt();
                if(r==0 && c==0)
                {
                    lg=a[r][c];
                    lr=r;
                    lc=c;
                    sm=a[r][c];
                    srw=r;
                    scl=c;
                }
                else if(a[r][c]>lg)
                {
                    lg=a[r][c];
                    lr=r;
                    lc=c;
                }
                else if(a[r][c]<sm)
                {
                    sm=a[r][c];
                    srw=r;
                    scl=c;
                }
            }
        }

        a[lr][lc]=sm;
        a[srw][scl]=lg;

        System.out.println("\nArray after interchanging largest with the smallest number");
        for(r=0; r<3; r++)
        {
            for(c=0; c<3; c++)
            {
                System.out.print(a[r][c]+" ");
            }
            System.out.println();
        }
    }
}

Output

Enter 9 numbers
5
12
18
2
17
23
45
96
62

Array after interchanging largest with the smallest number
5 12 18
96 17 23
45 2 62
video-poster