‹ Back to the paper
Design a class Colsum to check if the sum of elements in each corresponding column of two matrices…
Design a class Colsum to check if the sum of elements in each corresponding column of two matrices is equal or not. Assume that the two matrices have the same dimensions.
Example:
Input:
MATRIX A
MATRIX B
Output: Sum of corresponding columns is equal.
The details of the members of the class are given below:
Class name : Colsum
Data members/instance variables:
mat[ ][ ] : to store the integer array elements
m : to store the number of rows
n : to store the number of columns
Member functions/methods:
Colsum(int mm, int nn) : parameterised constructor to initialise the data members m = mm and n = nn
void readArray( ) : to accept the elements into the array
boolean check(Colsum A, Colsum B) : to check if the sum of elements in each column of the objects A and B is equal and return true otherwise, return false
void print( ) : to display the array elements
Specify the class Colsum giving details of the constructor(int, int), void readArray( ), boolean check(Colsum, Colsum), and void print( ). Define the main( ) function to create objects and call the functions accordingly to enable the task.
| 2 | 3 | 1 |
| 7 | 5 | 6 |
| 1 | 4 | 2 |
| 7 | 4 | 2 |
| 1 | 3 | 1 |
| 2 | 5 | 6 |
Answer
Answer
AIimport java.util.Scanner;
class Colsum
{
int mat[][];
int m, n;
Colsum(int mm, int nn)
{
m = mm;
n = nn;
mat = new int[m][n];
}
void readArray()
{
Scanner sc = new Scanner(System.in);
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
mat[i][j] = sc.nextInt();
}
boolean check(Colsum A, Colsum B)
{
for (int j = 0; j < A.n; j++)
{
int sumA = 0, sumB = 0;
for (int i = 0; i < A.m; i++)
{
sumA += A.mat[i][j];
sumB += B.mat[i][j];
}
if (sumA != sumB)
return false;
}
return true;
}
void print()
{
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
System.out.print(mat[i][j] + " ");
System.out.println();
}
}
public static void main(String[] args)
{
Colsum A = new Colsum(3, 3);
A.readArray();
Colsum B = new Colsum(3, 3);
B.readArray();
if (A.check(A, B))
System.out.println("Sum of corresponding columns is equal.");
else
System.out.println("Sum of corresponding columns is not equal.");
}
}Explanation: check(A,B) sums each column of A and the corresponding column of B and compares them; it returns false as soon as any pair of column sums differ, else true after checking all columns. Tested with the example matrices from the question - output: "Sum of corresponding columns is equal." (column sums 10,12,9 match on both sides).From ISC 2025 Computer Science Paper 1, question 7.