Adding Values of 2 Arrays

• 09-03-2009, 12:12 PM
core2duo5252
Adding Values of 2 Arrays
Kindly Help me Continue the code for this program. It should Display the sum of int myarray [][]= {{0,1,2},{1,0,3}};
int myarray1 [][]= {{1,2,3},{6,5,4}}; like 0 of myarray and 1 of myarray1. Thanks. Please Help:(

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author m303user
*/import java.io.*;
public class jun_pyo {

public static void main(String[] args) {
int myarray [][]= {{0,1,2},{1,0,3}};
int myarray1 [][]= {{1,2,3},{6,5,4}};

System.out.println("1st array :");
for(int row = 0; row < myarray.length; row++) {
for(int column = 0; column <= myarray.length;column++) {
System.out.print("" + myarray[row][column]);
}
System.out.println();
}
{
System.out.println("2nd array :");
for(int row = 0; row < myarray1.length;row++) {
for(int column = 0; column <= myarray1.length;column++) {
System.out.print(""+ myarray1[row][column]);

}
System.out.println(); for (int sum=0;sum<2;sum++)
{
System.out.println(" "+myarray1[row]);
}
}
}
}

}
• 09-03-2009, 12:23 PM
r035198x
What do you mean by the sum of a 2D array?
How did you get 0 for myarray and 1 for myarray1?
• 09-03-2009, 12:31 PM
mtyoung
what is the expect output of your example?
• 09-04-2009, 09:22 AM
core2duo5252
The output
Ok so this should be the Output of it

0 1 2 ---array1
1 0 3---array2

1 2 3----array1
6 5 4---array2

1 3 5====the sum of array 1
7 5 7====the sum of array 2
• 09-04-2009, 10:06 AM
r035198x
So you want to add two arrays the way matrix addition is done?
Better create an add method then that takes two arrays and returns an array.
Your add method should check that the two supplied arrays can be added together in the first place before trying to do the addition. The rest is just a bit of math. Try it and post a refined version.
• 09-04-2009, 12:30 PM
core2duo5252
...
Im really at loss at this one sir.. Can you not refine my program and rewrite it.
• 09-04-2009, 12:33 PM
r035198x
Not me, you. You do know how to declare a method right?
Just declare the method as I suggested taking two arrays and returning an array. Then you declare the array that will hold then sum.
After that you go over the two arrays adding elements at corresponding positions to their corresponding positions in the sum array.
Also include a separate method that determines if two arrays can be added together or not.
• 09-05-2009, 04:50 AM
mtyoung
do you know how to get the size of array?
like r035198x said, create a method with 2 input int[][] parameter and return int[][] array

then use 2 for loop (1 outer, 1 inner) to sum up the corresponding filed of array
assign the resultant value to any one of array, return the resultant array