Advertisements
Advertisements
प्रश्न
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 | ||||||
| 2 | 3 | 1 | 7 | 4 | 2 | ||
| 7 | 5 | 6 | 1 | 3 | 1 | ||
| 1 | 4 | 2 | 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): | 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 elements into the array |
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.
कोड लेखन
Advertisements
उत्तर
import java.util. Scanner;
class Colsum {
private int[][] mat;
private int m, n;
// Parameterized constructor
public Colsum(int mm, int nn) {
m = mm;
n = nn;
mat = new int[m][n];
}
// Function to read matrix elements
public void readArray(Scanner sc) {
System.out.println("Enter elements for a" + m +
"x" + n + "matrix");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
mat[i][j] = sc.nextInt();
}
}
}
// Function to print matrix
public void print (){
System.out.println("matrix elements:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(mat[i][j] + " ");
}
System.out.println();
}
}
// Function to check if column sums are equal
public static boolean check(Colsum A, Colcum 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;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of rows and
columns:");
int rows = sc.nextInt();
int cols = sc.nextInt();
// Creating two matrix objects
Colsum A = new Colsum(rows, cols);
Colsum B = new Colsum(rows, cols);shaalaa.com
क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
