how to contruct a 2d array given two sets code example

Example 1: adding elements in a specified column or row in a two dimensional array java

/* After the prompt code segment and sumOfCol in the main method */

    // Row (major index)
    for (int row = 0; row < matrix.length; row++) {
        int rowSum = 0;
        for (int col = 0; col < matrix[row].length; col++) {
            rowSum += matrix[row][col];
        }
        System.out.println("Sum of the elements at row " + row + " is: " + rowSum);
    }

    // Column (minor index)
    // Assuming the length of each row is the same
    for (int col = 0; col < matrix[0].length; col++) {
        int colSum = 0;
        for (int row = 0; row < matrix.length; row++) {
            colSum += matrix[row][col];
        }
        System.out.println("Sum of the elements at col " + col + " is: " + colSum);
    }

Example 2: 2d array java

//Length
int[][]arr= new int [filas][columnas];
arr.length=filas;

        int[][] a = {
            {1, 2, 3}, 
            {4, 5, 6, 9}, 
            {7}, 
        };
      
        // calculate the length of each row
        System.out.println("Length of row 1: " + a[0].length);
        System.out.println("Length of row 2: " + a[1].length);
        System.out.println("Length of row 3: " + a[2].length);
    }

Tags:

Cpp Example