1. Complete the following program so that it computes the maximum and minimum of the elements in the array. Write the program so that it works even if the dimensions of the rows and columns are changed. (Use length rather than hard-coded numbers.)
Think carefully about how max and min should be initialized. Debug your program by editing the array. Change it in unexpected ways, such as all negative values, or the largest element as the last, or first, or all elements the same.
import java.io.* ;
class ArrayMaxMin
{
public static void main ( String[] args )
{
int[][] data = { {3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8} };
// declare and initialize the max and the min
???
//
for ( int row=0; row < data.length; row++)
{
for ( int col=0; col < ???; col++)
{
???
}
}
// write out the results
System.out.println( "max = " + max + "; min = " + min );
}
}
2. Modify the program so that it computes and prints the largest element in each row.
Requirements: Looping, bounds checking, initializer lists.

Respuesta :

Answer:

See Explanation

Explanation:

The line by line explanation of the modified program is as follows:

(1)

min is declared and initialized to the highest possible integer and max is declared and initialized to the least possible integer

int min,max;

min = Integer.MAX_VALUE; max = Integer.MIN_VALUE;

This iterates through each row. Because each row has a different number of elements, the row length of each is calculated using data[row].length

for ( int [tex]col=0; col[/tex]< [tex]data[row].length[/tex]; col++){

The following if statements get the minimum and the maximum elements of the array

   if(data[row][col] < min){         [tex]min = data[row][col];[/tex]    }

   if(data[row][col] > max){         [tex]max = data[row][col];[/tex]     }

(2):

The loop remains the same, however, the print statement is adjusted upward to make comparison between each row and the highest of each row is printed after the comparison

for ( int [tex]row=0; row[/tex] < [tex]data.length;[/tex] row++){

for ( int [tex]col=0; col[/tex]< [tex]data[row].length;[/tex] col++){

   if(data[row][col] > max){         [tex]max = data[row][col];[/tex]     }

}

System.out.println( "max = " + max);

max = Integer.MIN_VALUE; }

See attachment for complete program that answers (1) and (2)

Ver imagen MrRoyal