Print the smallest number in a 3 x 3 matrix

Let's create another class for this exercise, name it InterviewMinnumber, and define the array in the main block. The definition code will be as follows:

int abc[][]={{2,4,5},{3,2,7},{1,2,9}};

This code declares a 3 x 3 matrix named abc. Now we need to traverse each number in the matrix, and look for the smallest number in it. To traverse every number in the multidimensional array, we need to use the same concept that we have used in the Logic programming on multidimensional arrays section.

We use two for loops here: an outer for loop to traverse the rows and an inner for loop to traverse the columns. The two for loops code will look at follows:

for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
}
}

To find the smallest number, we declare a variable, min, and assign the first value of the abc array to it. We assume that the first value in the abc matrix is the lowest value in it.

We add an if loop inside the inner for loop. Within this if loop, whatever we write will go and scan each element in the whole matrix that we declared. In the if loop, we add a condition where we check whether the value taken from the matrix at that instance is less than the min value. Inside the if loop, we swap the value of min and abc. The final code will be as follows:

public class InterviewMinnumber 
{
public static void main(String[] args)
{
int abc[][]={{2,4,5},{3,2,10},{1,2,9}};
int min=abc[0][0];
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
if(abc[i][j]<min)
{
min=abc[i][j];
}
}
}
System.out.println(min)
}
}

Let's run the code and see how it finds the smallest number in the matrix.

When the loop is executed first, the value of the first element in the matrix is compared to the value of the min variable, but we set the value of the min variable equal to the first element, which is 2. We check the condition in the if loop, which compares the value of the element in the matrix and the value of min. Here, 2 is not smaller than 2, so it does not enter the loop and it goes to the start of the code again. In the next round of the loop, the value of the element changes because we move the next element in the matrix. Now the element being compared is 4, we check the if condition again and it won't be true because 4 is not smaller that 2, where 2 is the current value of min. Finally, when it reaches the element in the third row first column, 1, then the if condition is true and the controller moves inside the loop and assigns 1 to the min value. This goes on until the final element in the array matrix, where each value of the abc matrix is compared to the value of the min variable.

If we debug the code and observe it at every step, we will better understand the logic and working of this code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.183.89