Java

Moderators: zibadian
Number of threads: 7836
Number of posts: 18235

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
Help with writing Arrays Posted by helen1974 on 19 Mar 2012 at 4:43 AM
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] + "\t" );
}
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);
}
}
Report
Re: Help with writing Arrays Posted by Wirus on 28 Mar 2012 at 3:04 AM
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] + "\t");
}
System.out.println();
}
System.out.println("\nMax value = " + max_val);
System.out.println("\nit's co-ordinates are row " + max_row_pos + " column " + max_col_pos);
}
}
Report
Re: Help with writing Arrays Posted by Wirus on 28 Mar 2012 at 3:06 AM
IGNORE - Duplicated by mistake



 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.