Dremendo Tag Line

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

Two Dimensional Array - Question 3

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

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

Program

import java.util.Scanner;

public class Q3
{
    public static void main(String args[])
    {
        int a[][]=new int[3][3], r,c,lg=0,sm=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];
                    sm=a[r][c];
                }
                else if(a[r][c]>lg)
                {
                    lg=a[r][c];
                }
                else if(a[r][c]<sm)
                {
                    sm=a[r][c];
                }
            }
        }
        System.out.println("Largest number = "+lg);
        System.out.println("Smallest number = "+sm);
    }
}

Output

Enter 9 numbers
63
24
15
3
75
2
19
31
42
Largest number = 75
Smallest number = 2
video-poster