KnowledgeBoat Logo
|

Computer Applications

Write a class program with the following specifications:

Class name — Matrix

Data members — int array m[][] with 3 rows and 3 columns

Member functions:

  1. void getdata() — to accept the numbers in the array
  2. void rowsum() — to find and print the sum of the numbers of each row
  3. void colsum() — to find and print the sum of numbers of each column

Use a main function to create an object and call member methods of the class.

Java

Encapsulation & Inheritance in Java

14 Likes

Answer

import java.util.Scanner;

public class Matrix
{
    private final int ARR_SIZE = 3;
    private int[][] m;
    
    public Matrix() {
         m = new int[ARR_SIZE][ARR_SIZE];
    }
    
    public void getdata() {
        Scanner in = new Scanner(System.in);
        for (int i = 0; i < ARR_SIZE; i++) {
            System.out.println("Enter elements of row " 
                + (i+1) + ":");
            for (int j = 0; j < ARR_SIZE; j++) {
                m[i][j] = in.nextInt();
            }
        }
    }
    
    public void rowsum() {
        for (int i = 0; i < ARR_SIZE; i++) {
            int rSum = 0;
            for (int j = 0; j < ARR_SIZE; j++) {
                rSum += m[i][j];
            }
            System.out.println("Row " + (i+1) + " sum: " + rSum);
        }
    }
    
    public void colsum() {
        for (int i = 0; i < ARR_SIZE; i++) {
            int cSum = 0;
            for (int j = 0; j < ARR_SIZE; j++) {
                cSum += m[j][i];
            }
            System.out.println("Column " + (i+1) + " sum: " + cSum);
        }
    }
    
    public static void main(String args[]) {
        Matrix obj = new Matrix();
        obj.getdata();
        obj.rowsum();
        obj.colsum();
    }
}

Variable Description Table

Program Explanation

Output

BlueJ output of Write a class program with the following specifications: Class name — Matrix Data members — int array m[][] with 3 rows and 3 columns Member functions: (a) void getdata() — to accept the numbers in the array (b) void rowsum() — to find and print the sum of the numbers of each row (c) void colsum() — to find and print the sum of numbers of each column Use a main function to create an object and call member methods of the class.

Answered By

5 Likes


Related Questions