Write a program to find greatest number in a 3*3 array

Write a program to find the greatest number in a 3*3 array.

The program is supposed to receive 9 integer numbers as command-line arguments.

Program to Print 3*3 array in Java

Reading 9 integer numbers as command-line arguments and assigning it to 3*3 matrix and printing it

Program Steps are

  1. Create a Java class
  2. declare a 3 by 3 matrix
  3. create two loops to read two dimensional array outer loop is for row and inner loops is for column
  4. Access command line argument values and store to array.
  5. display the array.

Here a[row][col]=Integer.parseInt(args[i]);

row and column is incremented by loop and to increase command line argument value variable i is used.

Output of above program is as below

9 integer numbers as command-line arguments in java
9 integer numbers as command-line arguments in java

Above program works properly if you provide correct number of arguments.

if argument is less then the desired count then it throws ArrayIndexOutOfBoundsException

java.lang.ArrayIndexOutOfBoundsException
java.lang.ArrayIndexOutOfBoundsException:

Checking Number of command line arguments in Java

As we already know String args[] is a command line argument, that is a String array.

To Check the array length we use length property of array in java.

Following code must be included to check the args length

Complete code after including this is as below

Expected Input and output as below

example1: c:\>java sample 1 2 3 o/p expected : please enter 9 integer numbers

Checking command-line arguments length
Checking command-line arguments length

Program to find greatest number in a 3*3 array

example2: c:\>java sample 1 23 45 55 121 222 56 77 89

o/p expected : the given array is : 1 23 45 55 121 222 56 77 89 the biggest number in the given array is 222

Steps to find Greatest number in array

  1. Declare an array
  2. Initialize array
  3. take a variable (ie greatest) to store greatest number and initialize to 0
  4. compare each element of array with greatest
  5. if array element is greater that greater then assign greater=array element
  6. print array ement
  7. print greater value

To find the greatest among array elements we declared a variable greatest and initialized to 0.

Now each time comparing greatest with array element and if array element is greater than variable greatest the assign array value to greatest.

find greatest number in a 3*3 array
find greatest number in a 3*3 array

Java method to find greatest number in a 3*3 array

Java method to return greatest number in a 3*3 array