import java.util.Scanner;

public class Homework1 {

    /**
     * @param args
     */
    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in); 
        final int ROW;
        final int COL;
        int integar;
        int total;

        System.out.println("Total number of rows: ");
        ROW = scan.nextInt();
        System.out.println("Total number of colums: ");
        COL = scan.nextInt();
        int [][] nums = new int [ROW][COL];

        for (int r = 0; r < ROW; r++){
            for (int c = 0; c < COL; c++){
                System.out.print("Enter a number: ");
                nums [r][c] = scan.nextInt();
            }
        }
        for (int r = 0; r < ROW; r++){
            for (int c = 0; c < COL; c++){
                System.out.print(nums [r][c] + " ");

            }
            System.out.println("");
        }
        for (int r = 0; r < ROW; r++){
            total = 0;
            for (int c = 0; c < COL; c++){
            total += nums [r][c];
            }

            System.out.println("Sum of each row " + "is " + total);
        }





            }

        }

Basically the assignment requires the sum of each row, which I have already and the sum of all elements of the array which I'm really stuck on for the past few hours. I know I need another for loop but really not sure how to write it

Edited 3 Years Ago by LegendX

Finding the sum of all elements of the array is the same as finding the sum of each row, except instead of setting total to zero at the start of each row, you don't do that.

As bguild said

take one more variable for sum_of_all_elements

and add all columns values of each row to this variable (in side for loop) like as
total variable

what i mean is

sum_of_all_elements += nums[r][c]

thats it

Edited 3 Years Ago by radhakrishna.p: giving clarity on the solution

 for (int r = 0; r < ROW; r++){
for (int c = 0; c < COL; c++){
total += nums [r][c];
}
System.out.println("Total " + "is " + total);
}

so it would look like this?

Why don't you just try that and see for yourself?
(It's nearly right, and when you try it you will see what's wrong and how to fix it)

This article has been dead for over six months. Start a new discussion instead.