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

Recommended Answers

All 4 Replies

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

 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)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.