Dear experts,

Please kindly advise me in how i should write the column operation:
The following is the full codes:

import java.util.*;

public class Matrix {

    public static void main(String[] args) {

        // declare the necessary variables

        int N, M;
        String operator;
        int index;
        int sum;
        int [][]matrix = new int[101][101];
      
        // we use 0-based arrary types
        Scanner sc = new Scanner(System.in);    
        N = sc.nextInt();
        M = sc.nextInt();
        for (int i = 0; i < N; i++)
        {
            for (int j = 0; j < M; j ++)
            {
                matrix[i][j] = sc.nextInt();
            }
        }
        operator = sc.next();
        index = sc.nextInt();
        sum = 0;
        index--;
        // since we 0-based but the problem requires 1-based

        if(operator.equals("ROW"))
        {
            for (int i = 0; i < M;  i++)
            {
                sum += matrix[index][i];
            }
        }
        else
        {
            // column operation
        }
System.out.println(sum);
    }
}

At the

// column operation

, i have tried to code the following:

else// if (operator.equals("COLUMN"))
{
// for (int i = 0; i < N; i--)
 for (int j = 0; j < M; j++){
  sum += matrix[j][index];
  } //System.out.println(sum);
}

However, it is unable to give me the output of 5 when my input is as the following:

10 6
0 1 0 0 0 1
0 1 0 1 0 1
0 1 1 1 1 0
1 1 1 0 1 0
1 0 1 0 0 0
0 1 0 0 1 1
0 1 1 0 1 1
0 0 0 0 0 0
1 0 0 0 1 0
0 1 1 1 0 0
COLUMN 3

instead i got the output of 3.

Could anyone please kindly guide me.
Thank you so much.

For columns, shouldn't you be doing:

for (int j = 0; j < N; j++){
  sum += matrix[j][index];
  }

With N.
When you enter values to the array you do:
>> for (int i = 0; i < N; i++)
>> for (int j = 0; j < M; j++)
>> matrix[j] =

So the N is when you access the first dimension(matrix[][]) and the M when you access the second dimension(matrix[][])


Also I would advise you to:
1)

// we use 0-based arrary types
        Scanner sc = new Scanner(System.in);    
        N = sc.nextInt();
        M = sc.nextInt();
int [][]matrix = new int[N][M];

2) For easier use:

System.out.println("Enter operator:");
operator = sc.next();
System.out.println("Enter Index:");
index = sc.nextInt();
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.