i have this array code that would give the sum of the random numbers in the columns, however i could not figure out how to display the sum of the rows.. can someone help.. Thanks a lot...

import java.util.*;
public class tabulated {
    public static void main(String[]args){

    Random rand=new Random();
    int [][]nos=new int[7][7];
   int sumc=0;
    for(int i=0;i<nos.length;i++){
    for(int l=0;l<nos[i].length;l++){
              nos[i][l]= rand.nextInt(100);

              sumc=nos [i][0]+nos [i][1]+nos [i][2];
        System.out.print( nos [i][l]+"\t" ); 

Do you want to show sum of each row? You are on the right track up until line 15. What you need is to add up the "sumc" with the value you just assigned to - nos[l] - not add the values as you are doing now (hard-coded). Also, you need to reset your "sumc" to 0 every time right before you call for column loop (the 2nd loop inside the first loop). Then it should be fine.

Member Avatar

My suggestions...
1. Move your contents of line 8 down to line 11. // initializes each row sum to 0
2. Change line 15 to sumc = sumc + nos [l]; // adds the number to the sum

how can i get the vertical sum?

57 92 4 =153
41 99 8 =148
55 13 2 =70
? ? ?

Switch the for loop statement?

Member Avatar

Have an array to hold your Column Sums.
Initialize them to 0 before your for loops.
Add your nos[l] to the Column Sum for the appropriate column.

If you just want to display on the console only (as you are doing now for horizontal sum), wouldn't it be easier to copy the whole for-loop, take out line 13, and switch line 10 and 12 instead of create another array?

Member Avatar

No... Not really.
The looping mechanics are already there.
Why would you want to recreate it?

Because doing so would make life more difficult. Even though a looping is there, it does not need to be reused in every case. :) Also, you would still have to loop through the newly created array to display the result. So copy, paste, and some modify would make life easier. When you are learning something new, you should not talk about optimization just yet. :)