VTU

VTU RESULTS

Java -Program 01 : Matrix Addition

Develop a JAVA program to add TWO matrices of suitable order N (The value of N should be read from command line arguments).

public class MatrixAddition {
    public static void main(String[] args) {
        // Check if the number of command line arguments is correct
        if (args.length != 1) {
            System.out.println("Usage: java MatrixAddition <order_N>");
            return;
        }

        // Parse the command line argument to get the order N
        int N = Integer.parseInt(args[0]);

        // Check if N is a positive integer
        if (N <= 0) {
            System.out.println("Please provide a valid positive integer for the order N.");
            return;
        }

        // Create two matrices of order N
        int[][] matrix1 = new int[N][N];
        int[][] matrix2 = new int[N][N];

        // Fill the matrices with some sample values (you can modify this as needed)
        fillMatrix(matrix1, 1);
        fillMatrix(matrix2, 2);

        // Print the matrices
        System.out.println("Matrix 1:");
        printMatrix(matrix1);

        System.out.println("\nMatrix 2:");
        printMatrix(matrix2);

        // Add the matrices
        int[][] resultMatrix = addMatrices(matrix1, matrix2);

        // Print the result matrix
        System.out.println("\nResultant Matrix (Matrix1 + Matrix2):");
        printMatrix(resultMatrix);
    }

    // Helper method to fill a matrix with sequential values
    private static void fillMatrix(int[][] matrix, int startValue) {
        int value = startValue;
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                matrix[i][j] = value++;
            }
        }
    }

    // Helper method to add two matrices
    private static int[][] addMatrices(int[][] matrix1, int[][] matrix2) {
        int N = matrix1.length;
        int[][] resultMatrix = new int[N][N];

        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                resultMatrix[i][j] = matrix1[i][j] + matrix2[i][j];
            }
        }

        return resultMatrix;
    }

    // Helper method to print a matrix
    private static void printMatrix(int[][] matrix) {
        for (int[] row : matrix) {
            for (int value : row) {
                System.out.print(value + "\t");
            }
            System.out.println();
        }
    }
}

Main Method:

  • Command-Line Argument Check:
if (args.length != 1) {
    System.out.println("Usage: java MatrixAddition <order_N>");
    return;
}

this checks if exactly one command-line argument is provided. If not, it prints a usage message and exits.

Parse Order N:

int N = Integer.parseInt(args[0]);

The program parses the command-line argument to an integer, which represents the order of the matrices.

Validation of N:

if (N <= 0) {
    System.out.println("Please provide a valid positive integer for the order N.");
    return;
}

It checks if N is a positive integer. If not, it prompts the user to provide a valid value and exits.

Matrix Initialization:

int[][] matrix1 = new int[N][N];
int[][] matrix2 = new int[N][N];

Two matrices, matrix1 and matrix2, are created with dimensions N×N times N×N.

Filling the Matrices:

  • Sequential Value Filling
fillMatrix(matrix1, 1);
fillMatrix(matrix2, 2);

The fillMatrix method is called to fill each matrix with sequential values starting from 1 for matrix1 and 2 for matrix2. This is just for demonstration, and you can modify this logic if needed.

Printing the Matrices:

  • The program prints both matrices using the printMatrix method
System.out.println("Matrix 1:");
printMatrix(matrix1);

System.out.println("\nMatrix 2:");
printMatrix(matrix2);

Matrix Addition:

  • The addMatrices method is called to perform element-wise addition of the two matrices
int[][] resultMatrix = addMatrices(matrix1, matrix2);

Displaying the Result Matrix:

  • The resultant matrix after addition is printed:
System.out.println("\nResultant Matrix (Matrix1 + Matrix2):");
printMatrix(resultMatrix);

Helper Methods:

  1. fillMatrix:
private static void fillMatrix(int[][] matrix, int startValue) {
    int value = startValue;
    for (int i = 0; i < matrix.length; i++) {
        for (int j = 0; j < matrix[i].length; j++) {
            matrix[i][j] = value++;
        }
    }
}

This method fills a matrix with sequential integers starting from a specified value. It iterates through each row and column, assigning values in a sequential manner.

addMatrices:

private static int[][] addMatrices(int[][] matrix1, int[][] matrix2) {
    int N = matrix1.length;
    int[][] resultMatrix = new int[N][N];

    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            resultMatrix[i][j] = matrix1[i][j] + matrix2[i][j];
        }
    }

    return resultMatrix;
}

This method takes two matrices and returns a new matrix that is the result of their element-wise addition.

printMatrix:

private static void printMatrix(int[][] matrix) {
    for (int[] row : matrix) {
        for (int value : row) {
            System.out.print(value + "\t");
        }
        System.out.println();
    }
}

This method prints a given matrix in a tabular format, making it easier to visualize.


If you want to modify the fillMatrix method to read values for the matrix from command line arguments instead of filling it with sequential values, you can do the following:

  1. Change the Method Signature: Update the fillMatrix method to take an array of strings as an argument, representing the values.
  2. Parse the Command Line Arguments: Adjust your main method to collect and pass these values to fillMatrix.

Here’s how you can modify your code:

import java.util.Scanner;

public class MatrixAddition {
    public static void main(String[] args) {
        // Check if the number of command line arguments is correct
        if (args.length != 1) {
            System.out.println("Usage: java MatrixAddition <order_N>");
            return;
        }

        // Parse the command line argument to get the order N
        int N = Integer.parseInt(args[0]);

        // Check if N is a positive integer
        if (N <= 0) {
            System.out.println("Please provide a valid positive integer for the order N.");
            return;
        }

        // Create two matrices of order N
        int[][] matrix1 = new int[N][N];
        int[][] matrix2 = new int[N][N];

        // Read matrix values from command line
        System.out.println("Enter values for Matrix 1 (total " + (N * N) + " values):");
        fillMatrix(matrix1, N);

        System.out.println("Enter values for Matrix 2 (total " + (N * N) + " values):");
        fillMatrix(matrix2, N);

        // Print the matrices
        System.out.println("Matrix 1:");
        printMatrix(matrix1);

        System.out.println("\nMatrix 2:");
        printMatrix(matrix2);

        // Add the matrices
        int[][] resultMatrix = addMatrices(matrix1, matrix2);

        // Print the result matrix
        System.out.println("\nResultant Matrix (Matrix1 + Matrix2):");
        printMatrix(resultMatrix);
    }

    // Modified method to fill a matrix with values from user input
    private static void fillMatrix(int[][] matrix, int N) {
        Scanner scanner = new Scanner(System.in);
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                matrix[i][j] = scanner.nextInt(); // Read value from input
            }
        }
    }

    // Helper method to add two matrices
    private static int[][] addMatrices(int[][] matrix1, int[][] matrix2) {
        int N = matrix1.length;
        int[][] resultMatrix = new int[N][N];

        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                resultMatrix[i][j] = matrix1[i][j] + matrix2[i][j];
            }
        }

        return resultMatrix;
    }

    // Helper method to print a matrix
    private static void printMatrix(int[][] matrix) {
        for (int[] row : matrix) {
            for (int value : row) {
                System.out.print(value + "\t");
            }
            System.out.println();
        }
    }
}

Summary

The program efficiently handles matrix addition, includes command-line input validation, and utilizes helper methods for clarity and modularity. You can easily modify it to accept user input for matrix values instead of using sequential filling if desired.


Discover more from VTU

Subscribe to get the latest posts sent to your email.

Leave a Reply

Your email address will not be published. Required fields are marked *