6.9k views
0 votes
java Find the maximum value and minimum value in milesTracker. Assign the maximum value to maxMiles, and the minimum value to minMiles. Sample output for the given program:

User Anagio
by
7.7k points

1 Answer

4 votes

Answer:

Here is the complete code:

import java.util.Scanner; //to accept input from user

public class Main { //class name

public static void main (String [] args) { //start of main method

final int NUM_ROWS = 2; //sets number of rows to 2

final int NUM_COLS = 2; //sets number of columns to 2

int [][] milesTracker = new int[NUM_ROWS][NUM_COLS]; // creates an array of 2 rows and 2 columns

int i = 0; //sets i to 0

int j = 0; //sets j to 0

int maxMiles = 0; //to store maximum value

int minMiles = 0; //to store minimum value

//enter elements in milesTracker 2 dimensional array

milesTracker[0][0] = -10;

milesTracker[0][1] = 20;

milesTracker[1][0] = 30;

milesTracker[1][1] = 40;

maxMiles = milesTracker[0][0]; //assigns value at 0th row and 0th column of milesTracker array to maxMiles initially

minMiles = milesTracker[0][0]; //assigns value at 0th row and 0th column of milesTracker array to minMiles

for(i = 0; i <= NUM_ROWS - 1; i++){ //iterates through rows of array

for(j = 0; j <= NUM_COLS - 1; j++){ //iterates through columns

if(milesTracker[i][j] < minMiles){ //if a value at i-th row and j-th column of milesTracker array is less than value of minMiles

minMiles = milesTracker[i][j]; } //sets that value to minMiles (so the minimum value is set to minMiles)

if(milesTracker[i][j] > maxMiles){ //if a value at i-th row and j-th column of milesTracker array is greater than value of maxMiles

maxMiles = milesTracker[i][j]; } } } //sets that value to maxMiles (so the maximum value is set to minMiles)

System.out.println("Min miles: " + minMiles); //displays minimum value

System.out.println("Max miles: " + maxMiles); }} //displays maximum value

Step-by-step explanation:

The outer loop iterates through each row and the inner loop iterate through each column. The if condition in inner loop checks if the element at ith row and jth column is less than the minimum value i.e. the value stored in minMiles. If this condition evaluates to true then the element at ith and jth column is assigned to minMiles. Then the program moves to the next if condition which checks if the element at ith row and jth column is greater than the maximum value i.e. the value stored in maxMiles. If this condition evaluates to true then the element at ith and jth column is assigned to maxMiles. This is how the minimum and the maximum value in milesTracker array are found. After the loops break, the last two print statements print the maximum and minimum values. The screenshot of the program along with its output is attached.

java Find the maximum value and minimum value in milesTracker. Assign the maximum-example-1
User Vonjd
by
6.4k points