• October 22nd, 2011, 05:26 AM
dambundos
Dear all,
I wish to write a Java application program and an applet program that find the sum of all the integers in the array shown below and print them out together with the sum as below:

int[ ][ ]MyArray={{2, 3, 4, 5 }, {6, 7,8}, {9, 10}, {11}}

expected output:

2 3 4 5
6 7 8
9 10
11
Total = 28 20 12 5

(eg col1 6+2+9+11=28, col2: 3+7+10=20, col3: 8+4=12, col4: 5)

That is, the program arranges all first elements in one column, all second elements in another vertical column, etc and displays as output as shown above.. Then it sums them up the corresponding elements and displays them as Total = 24 17 10 4 as above. When I try, am getting wrong values for the sum and am unable to display the elements in vertical column.

Here is my code for the application program part:
public class AssignmtOneQuiz1 {

public static void main(String args[]) {
int sum = 0;

int[ ][ ]MyArray={{2, 3, 4, 5 }, {6, 7,8}, {9, 10}, {11}};

System.out.print("Total = ");
for(int i=0; i<MyArray.length; i++)
{

for(int j=0; j<MyArray[i].length; j++)
sum += MyArray[i][j];
System.out.print(sum + " ");
}

}

Butt it's not giving the required results. lease assist.
Thanks

}
• October 27th, 2011, 06:19 AM
daniel.j2ee
Everytime you're outputting the "sum", which accumulates all your terms, so this is why you get higher and higher values everytime. At some point, you need to stop accumulating the past values, and start with the new ones.

Got it? :)

application context
• November 4th, 2011, 04:17 AM
dambundos
Hi Daniel. Got it.
Infact the code now works perfect.

However, it only works as an application. How can I write the same code such that it is done in an applet this time and not application since application is ok?