Problem Description: Write the following method that returns the smallest elemen
ID: 3598528 • Letter: P
Question
Problem Description: Write the following method that returns the smallest element in a two-dimensional array along with its location (i.e., the row and column indices)
public static int[] findingSmallest(int [][] a)
The return value of the method must be a one-dimensional array that contains three elements. These three elements indicate the smallest value, row and column indices of its location in the two-dimensional array.
Write a test program that prompts the user to enter a two-dimensional array and displays the smallest element and its location in the array as shown in the following sample runs:
Sample 1
Enter the number of rows and columns of the array: 2 3
Enter the array: 8 9 5 7 3 10
The smallest element in the array is 3
The location of the smallest element is at (1, 1)
Sample 2
Enter the number of rows and columns of the array: 3 4
Enter the array: 1 2 3 4 5 6 7 8 1 1 1 1
The smallest element in the array is 1
The location of the smallest element is at (0, 0)
Sample 3
Enter the number of rows and columns of the array: 4 5
Enter the array: 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 -1 -2 -3 -4
The smallest element in the array is -4
The location of the smallest element is at (3, 4)
Explanation / Answer
FindingSmallestTest.java
import java.util.Scanner;
public class FindingSmallestTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of the array:");
int row = scan.nextInt();
int col = scan.nextInt();
int a[][] = new int[row][col];
System.out.println("Enter the array:");
for(int i=0;i<row;i++) {
for(int j=0;j<col;j++) {
a[i][j]=scan.nextInt();
}
}
int s[] = findingSmallest(a);
System.out.println("The smallest element in the array is "+s[0]);
System.out.println("The location of the smallest element is at ("+s[1]+", "+s[2]+")");
}
public static int[] findingSmallest(int [][] a) {
int s[] = new int[3];
s[0]=a[0][0];
s[1]=0;
s[2]= 0;
for(int i=0;i<a.length;i++) {
for(int j=0;j<a[i].length;j++) {
if(s[0] > a[i][j]) {
s[0]=a[i][j];
s[1]=i;
s[2]=j;
}
}
}
return s;
}
}
Output:
Enter the number of rows and columns of the array:
2 3
Enter the array:
8 9 5 7 3 10
The smallest element in the array is 3
The location of the smallest element is at (1, 1)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.