Results 1 to 3 of 3
  1. #1
    dutchgold92 is offline Member
    Join Date
    Feb 2011
    Posts
    8
    Rep Power
    0

    Default 2D Array - Sum of columns

    I'm doing a class exercise featuring an array of arrays, requiring me to calculate the sum of all array elements, the sum of each row, and the sum of each column. The latter I can't understand how to do.

    Here's the program - some parts are temporary, just included to ease the editing for me.
    Java Code:
    	public static void main(String[] args)
    	{
    		final int array[][] = new int[6][4];
    		int total = 0;
    		int rowTotal[] = new int[6];
    		int columnTotal[] = new int[4];
    
    
    		for (int i = 0; i < array.length; i++)
    			for (int x = 0; x < 4; x++)
    			{
    				array[i][x] = (int)(Math.random() * 10000) % 10 + 1;
    
    				System.out.println(i + "\t" + x + "\t" + array[i][x]);
    
    				total = total + array[i][x];
    				rowTotal[i] = rowTotal[i] + array[i][x];
    				columnTotal[x] = columnTotal[x] + array[x][x];
    			}
    
    		System.out.println("Total: " + total);
    		System.out.println("Total for row one: " + rowTotal[0]);
    		System.out.println("Total for column one: " + columnTotal[0]);
    	}

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,310
    Blog Entries
    7
    Rep Power
    20

    Default

    Change one line to the following and you're in business:

    Java Code:
    columnTotal[x] = columnTotal[x] + array[i][x];
    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    dutchgold92 is offline Member
    Join Date
    Feb 2011
    Posts
    8
    Rep Power
    0

    Default

    Quote Originally Posted by JosAH View Post
    Change one line to the following and you're in business:

    Java Code:
    columnTotal[x] = columnTotal[x] + array[i][x];
    kind regards,

    Jos
    No idea how I didnt get that. :o Cheers.

Similar Threads

  1. multiplying columns by row in 2d array
    By HarlanEllisonOverDrive in forum New To Java
    Replies: 0
    Last Post: 11-15-2010, 03:06 AM
  2. how to add columns from Matrices(2D array)
    By John_shok in forum New To Java
    Replies: 7
    Last Post: 10-04-2010, 04:33 PM
  3. Jlist Columns
    By DenRed in forum New To Java
    Replies: 2
    Last Post: 10-02-2009, 09:33 AM
  4. Counting the number of columns in a 2D array,
    By KalEl in forum New To Java
    Replies: 9
    Last Post: 10-21-2008, 05:27 AM
  5. Two diM aRRay and add rows and columns....
    By filly444 in forum New To Java
    Replies: 2
    Last Post: 08-30-2008, 05:24 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •