Help with writing Arrays - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

Help with writing Arrays

Posts: 4Member
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);
}
}

• Posts: 10Member
Hi Helen,

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);
}
}
• Posts: 10Member
IGNORE - Duplicated by mistake