Create a function file that uses nested loops you can choose
Create a function file that uses nested loops (you can choose for or while loops) to calculate the sum (one number) of any size matrix. You may not use built in functions other than length in your function. The matrix should be an input the function and the sum an output.
Solution
MatrixSum.java
 import java.util.Scanner;
 public class MatrixSum {
  
    public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.print(\"Enter the rows: \");
    int rows = scan.nextInt();
    System.out.print(\"Enter the columns: \");
    int cols = scan.nextInt();
    int a[][] = new int[rows][cols];
    for(int i=0; i<rows; i++){
        for(int j=0; j<cols; j++){
            System.out.print(\"Enter the value: \");
            a[i][j] = scan.nextInt();
        }
    }
    int sum = calcSum(a);
    System.out.println(\"The sum of matrix is: \"+sum);
    }
    public static int calcSum(int a[][]){
    int sum =0;
    for(int i=0; i<a.length; i++){
        for(int j=0; j<a[i].length; j++){
            sum = sum + a[i][j];
        }
    }
    return sum;
    }
}
Output:
Enter the rows: 3
 Enter the columns: 3
 Enter the value: 1
 Enter the value: 2
 Enter the value: 3
 Enter the value: 4
 Enter the value: 5
 Enter the value: 6
 Enter the value: 7
 Enter the value: 8
 Enter the value: 9
 The sum of matrix is: 45

