Hi All,
Is there a shorter way to achieve the following code, its a simple array table which is 3 rows by 4 columns. Each number in the table is multiplied by 3 and then the max value position is given by identifying its position in the table, ie max_value is 33, its position is row 1, column 4
Any help would be brilliant.
import java.util.Scanner;
public class page63
{
public static void main(String []args)
{
Scanner myinput = new Scanner(System.in);
int [][] table = {{0,1,11,3},{8,9,10,11},{4,5,6,1}};
int i,j;
int NO_OF_ROWS = 3;
int NO_OF_COLS = 4;
int max_val = table[0][0];
int max_row_pos = 0;
int max_col_pos = 0;
for(i=0; i < NO_OF_ROWS; i++)
{
for(j=0; j < NO_OF_COLS; j++)
{
table[i][j] = table[i][j]*3;
}
}
for(i=0; i < NO_OF_ROWS; i++)
{
for(j=0; j < NO_OF_COLS; j++)
{
System.out.print(table[i][j] + " " );
}
System.out.println();
}
for(i=0; i < NO_OF_ROWS; i++)
{
for(j=0; j < NO_OF_COLS; j++)
{
if(table[i][j]>max_val)
{
max_val=table[i][j];
max_row_pos=i+1;
max_col_pos=j+1;
}
}
}
System.out.println(" ");
System.out.println("Max value = "+max_val);
System.out.println(" ");
System.out.println("it's co-ordinates are row "+max_row_pos+" column "+max_col_pos);
}
}
Comments
I don't know if you still need this, but anyway... you could do this without repeating all these for loops, like:
public class page63 {
public static void main(String[] args) {
int[][] table = { { 0, 1, 11, 3 }, { 8, 9, 10, 11 }, { 4, 5, 6, 1 } };
int max_val = table[0][0];
int max_row_pos = 0;
int max_col_pos = 0;
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
table[i][j] = table[i][j] * 3;
if (table[i][j] > max_val) {
max_val = table[i][j];
max_row_pos = i + 1;
max_col_pos = j + 1;
}
System.out.print(table[i][j] + " ");
}
System.out.println();
}
System.out.println("
Max value = " + max_val);
System.out.println("
it's co-ordinates are row " + max_row_pos + " column " + max_col_pos);
}
}