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:
| 2 | 3 | 1 |
| 7 | 5 | 6 |
| 1 | 4 | 2 |
| 7 | 4 | 2 |
| 1 | 3 | 1 |
| 2 | 5 | 6 |
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): parameterized constructor to initialize 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, 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.
import java.util.Scanner;
class Colsum{
int mat[][];
int m;
int n;
public Colsum(int mm, int nn){
m = mm;
n = nn;
mat = new int[m][n];
}
public void readArray(){
Scanner in = new Scanner(System.in);
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
mat[i][j] = Integer.parseInt(in.nextLine());
}
}
}
public boolean check(Colsum A, Colsum B){
for(int i = 0; i < n; i++){
int sumA = 0;
int sumB = 0;
for(int j = 0; j < m; j++){
sumA += A.mat[j][i];
sumB += B.mat[j][i];
}
if(sumA != sumB)
return false;
}
return true;
}
public void print(){
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++)
System.out.print(mat[i][j] + "\t");
System.out.println();
}
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Number of rows: ");
int rows = Integer.parseInt(in.nextLine());
System.out.print("Number of columns: ");
int cols = Integer.parseInt(in.nextLine());
Colsum m1 = new Colsum(rows, cols);
Colsum m2 = new Colsum(rows, cols);
System.out.println("Enter Matrix A Elements:");
m1.readArray();
System.out.println("Enter Matrix B Elements:");
m2.readArray();
System.out.println("Matrix A");
m1.print();
System.out.println("Matrix B");
m2.print();
if(m1.check(m1, m2))
System.out.println("Column sums are same!");
else
System.out.println("Column sums are not same.");
}
}