Reputation: 63
public class colum {
public static void main(String[] args) {
int[][] data = {
{ 3, 2, 5,-45 },
{ 1, 4, 4, -8 },
{ 9, 6, -100, -2 },
{-10, 3, 1, -2 }};
for (int row = 0; row < data.length; row++) {
int large = data[row][0],
small = data[row][0];
for (int col = 0; col < data[row].length; col++) {
if (large < data[row][col]) {
large = data[row][col];
}if (small > data[row][col]) {
small = data[row][col];
}
}
System.out.println("\nlargest values:" + large);
large = 0;
System.out.println("smallest values:" +small);
small = 0;
}
}
}
Output is:
largest values:5 smallest values:-45
largest values:4 smallest values:-8
largest values:9 smallest values:-100
largest values:3 smallest values:-10
Upvotes: 2
Views: 2090
Reputation: 291
for (int col = 0; col < data[0].length; col++) {
int large = data[0][col],
small = data[0][col];
for (int row = 1; row < data.length; row++) {
if (large < data[row][col]) {
large = data[row][col];
}
if (small > data[row][col]) {
small = data[row][col];
}
}
System.out.print("\nlargest values:" + large);
System.out.print("smallest values:" +small);
}
Just chance your looping statement with this will give you the desired output.
Hopefully that helps.
Upvotes: 1
Reputation: 11174
Declare those outside the loop:
int large = data[row][0],
int small = data[row][0];
and initialise them simply to the first element:
int large = data[0][0],
int small = data[0][0];
Upvotes: 0
Reputation: 394126
Switch the order of the loops in order to find column wise minimum and maximum:
for (int col = 0; col < data[0].length; col++) { // assuming all row have same length
int large = data[0][col],
small = data[0][col];
for (int row = 1; row < data.length; row++) {
if (large < data[row][col]) {
large = data[row][col];
}
if (small > data[row][col]) {
small = data[row][col];
}
}
System.out.println("\nlargest values:" + large);
System.out.println("smallest values:" +small);
}
Output:
largest values:9
smallest values:-10
largest values:6
smallest values:2
largest values:5
smallest values:-100
largest values:-2
smallest values:-45
Upvotes: 2