Dremendo Tag Line

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

Two Dimensional Array - Question 9

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

Q9) Write a program in Java to input numbers in a 3X3 integer matrix (2d array) and print the largest number in each row.

Program

import java.util.Scanner;

public class Q9
{
    public static void main(String args[])
    {
        int a[][]=new int[3][3], r,c,lg=0,x=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();
            }
        }

        for(r=0; r<3; r++)
        {
            x=0;
            for(c=0; c<3; c++)
            {
                System.out.print(a[r][c]+" ");
                if(x==0)
                {
                    lg=a[r][c];
                    x=1;
                }
                else if(a[r][c]>lg)
                {
                    lg=a[r][c];
                }
            }
            System.out.println("  Largest Number = "+lg);
        }
    }
}

Output

Enter 9 numbers
18
12
5
10
15
45
38
72
64
18 12 5   Largest Number = 18
10 15 45   Largest Number = 45
38 72 64   Largest Number = 72
video-poster