Java implementation of Transposing Matrix

              Transposing a matrix deals with the same matrix with some modifications. Here,the rows become columns and columns became rows.

To implement this concept in java, follow the below steps.

Logic:

  • First, get the dimensions for the matrix from the user.
  • Read the elements of the input matrix.
  • Create the transpose matrix structure.
  • Using two for loops, change the columns into rows and rows into columns.
  • Finally, print the transpose matrix as output.

Program:

import java.util.Scanner;

public class TransposeMatrixEg {

    public static void main(String[] args) {

      Scanner s1 = new Scanner(System.in);

         // Get the dimensions of matrix

        System.out.print("Enter rows for the matrix: ");

        int rows = s1.nextInt();

        System.out.print("Enter columns for the matrix: ");

        int cols = s1.nextInt();

        int[][] matrix_1 = new int[rows][cols];

         // read the input for Matrix

        System.out.println("Enter the elements for the matrix:");

        for (int i = 0; i < rows; i++) {

            for (int j = 0; j < cols; j++) {

                matrix_1[i][j] = s1.nextInt();

            }

        }

        //Tranpose matrix initialisation and conversion       

        int[][] transpose = new int[cols][rows];

        for (int i = 0; i < rows; i++) {

            for (int j = 0; j < cols; j++) {

                transpose[j][i] = matrix_1[i][j];

            }

        }

         // Print the transpose matrix

        System.out.println("Transpose of the matrix:");

        for (int i = 0; i < cols; i++) {

            for (int j = 0; j < rows; j++) {

                System.out.print(transpose[i][j] + " ");

            }

            System.out.println();

        }

    }

}

Output:

              Compile and run the program to get the output.

C:\raji\blog>javac TransposeMatrixEg.java

C:\raji\blog>java TransposeMatrixEg

Enter rows for the matrix: 3

Enter columns for the matrix: 3

Enter the elements for the matrix:

1

2

3

4

5

6

7

8

9

Transpose of the matrix:

1 4 7

2 5 8

3 6 9

This is the way of creating the java program to implement the transpose matrix. Hope this blog is useful to you. Keep coding!!!

Java Program to calculate the sum of rows and columns in a matrix

              Matrix is a mathematical structure which consists of rows and columns. When you want to add the values of rows  and columns separately , follow the steps given below.

  • First, get the number of rows and columns from the user.
  • Initialise a new matrix with user’s rows and columns value.
  • Using a for loop, read the input for the matrix.
  • For calculating the sum of rows, use a for loop. Keep the row, navigate all column values and add the values. Do this for each row.
  • To make the sum of column values, keep the column, iterate the row values and add the value. Continue for all columns.
  • Finally, print the value.

Program:

import java.util.Scanner;

public class mRowColSum {

    public static void main(String[] args) {

        Scanner s1 = new Scanner(System.in);

       // get the matrix dimensions values

        System.out.print("Enter the number of rows: ");

        int row = s1.nextInt();

        System.out.print("Enter the number of columns: ");

        int col = s1.nextInt();

        int[][] matrix1 = new int[row][col];

        // read the matrix elements from the user

        System.out.println("Enter the matrix elements:");

        for (int i = 0; i < row; i++) {

            for (int j = 0; j < col; j++) {

                matrix1[i][j] = s1.nextInt();

            }

        }

      //Print the matrix

       System.out.println("The Matrix is :");

       for (int i = 0; i < row; i++) {

            for (int j = 0; j < col; j++) {

                System.out.print(matrix1[i][j] + " ");

            }

            System.out.println(" ");

        }

        // Calculation part and display the sum of rows value

        System.out.println("Sum of rows calculation:");

        for (int i = 0; i < row; i++) {

            int rowSum1 = 0;

            for (int j = 0; j < col; j++) {

                rowSum1 += matrix1[i][j];

            }

            System.out.println("Row " + (i + 1) + ": " + rowSum1);

        }

        // Calculation and display sum of columns value

        System.out.println("Sum of the columns:");

        for (int j = 0; j < col; j++) {

            int colSum1 = 0;

            for (int i = 0; i < row; i++) {

                colSum1 += matrix1[i][j];

            }

            System.out.println("Column " + (j + 1) + ": " + colSum1);

        }

        s1.close();

    }

}

Output:

C:\raji\blog>javac mRowColSum.java

C:\raji\blog>java mRowColSum

Enter the number of rows: 3

Enter the number of columns: 3

Enter the matrix elements:

1

1

2

3

4

5

6

7

8

The Matrix is :

1 1 2

3 4 5

6 7 8

Sum of rows calculation:

Row 1: 4

Row 2: 12

Row 3: 21

Sum of the columns:

Column 1: 10

Column 2: 12

Column 3: 15

That’s the java program to find the sum of rows and columns was written and executed successfully. Hope this code is useful to you. Keep Coding!!!!

Implementation of Matrix multiplication in java

              Matrix is one of the fundamental concepts in java. A matrix is a structure which consists of rows and columns.

Logic behind matrix multiplication:

  • When you want to multiply two matrices, there are some points to be noted.
  • First, columns of first matrix and rows of second matrix should be equal.
  • Iterate through each row of matrix1 and each column of matrix2 and add the elements.
  • Final result matrix rows should be equal to matrix1. The resultant matrix column should be equal to matrix2.

Program implementation:

  • It starts with including the built in package java.util.Scanner.
  • A public class is created with main() function.
  • A scanner object gets assigned with System input.
  • The dimensions of two matrices (rows and columns) received from the user. The columns of first matrix are equal to the rows of second matrix.
  • The values for first and second matrices are get assigned from user input.
  • Using three for loops, the rows are iterated with columns and added its value.
  • Finally, it gets assigned to result_matrix.
  • At last, the result_matrix is displayed in the screen.

Program:

import java.util.Scanner;

public class MMultiplicationExample {

    public static void main(String[] args) {

        Scanner s1 = new Scanner(System.in);

        // Get the dimensions of matrix

        System.out.print("Enter rows for first matrix: ");

        int r1 = s1.nextInt();

        System.out.print("Enter columns for first matrix / rows for second matrix: ");

        int cR = s1.nextInt();

        System.out.print("Enter columns for second matrix: ");

        int c2 = s1.nextInt();

        // Let us Initialize matrices

        int[][] matrix_1 = new int[r1][cR];

        int[][] matrix_2 = new int[cR][c2];

        int[][] result_matrix = new int[r1][c2];

        // read the input for Matrix 1

        System.out.println("Enter the elements for the first matrix:");

        for (int i = 0; i < r1; i++) {

            for (int j = 0; j < cR; j++) {

                matrix_1[i][j] = s1.nextInt();

            }

        }

        //read the input for Matrix 2

        System.out.println("Enter the elements for the second matrix:");

        for (int i = 0; i < cR; i++) {

            for (int j = 0; j < c2; j++) {

                matrix_2[i][j] = s1.nextInt();

            }

        }

        // Multiply the matrices

        for (int i = 0; i < r1; i++) {

            for (int j = 0; j < c2; j++) {

                result_matrix[i][j] = 0;

                for (int k = 0; k < cR; k++) {

                    result_matrix[i][j] += matrix_1[i][k] * matrix_2[k][j];

                }

            }

        }

        // Display the Resultant matrix

        System.out.println("Here is the Resultant matrix:");

        for (int i = 0; i < r1; i++) {

            for (int j = 0; j < c2; j++) {

                System.out.print(result_matrix[i][j] + " ");

            }

            System.out.println();

        }

        s1.close();

    }

}

Output:

C:\raji\blog>javac MMultiplicationExample.java

C:\raji\blog>java MMultiplicationExample

Enter rows for first matrix: 3

Enter columns for first matrix / rows for second matrix: 2

Enter columns for second matrix: 2

Enter the elements for the first matrix:

1

2

3

4

5

6

Enter the elements for the second matrix:

3

6

9

2

Here is the Resultant matrix:

21 10

45 26

69 42

That’s all. The java implementation of Matrix Multiplication is done. Hope, you are interested in this code. Keep coding.

Decimal to Binary conversion Programs in java

               Numbers are magical in mathematics. Decimal numbers are whole numbers, where the binary numbers contain 0’s and 1’s.

How to implement?

There are two methods to implement this program in java.

  1. 1.      Using user defined code
  2. 2.      Using Built-in function.

Let us implement this program in both ways.

1.Using user defined code:

It has following steps.

  • ·       First, read the input from the user.
  • ·       Using a while loop, until the decimal_no is greater than zero, repeat the process.
  • ·       using mod function, find the remainder using mod by 2.
  • ·       Next, decimal_no is divided by 2.
  • ·       Finally, print the binary_no.

Program:  

 import java.util.Scanner;

public class DecimalToBinaryEg1 {

    public static void main(String[] args) {

        Scanner s1 = new Scanner(System.in);

        // Read the Decimal number as input

        System.out.print("Enter the decimal number: ");

        int decimal_no = s1.nextInt();

        String binary_no = "";

        // Let us Convert the logic

        while (decimal_no > 0) {

            binary_no = (decimal_no % 2) + binary_no;

            decimal_no = decimal_no / 2;         

        }

        // Display the Binary number

        System.out.println("Binary number of decimal number: " + binary_no);

        s1.close();

    }

}

Output:

Compile and run the program to get the output.

C:\raji\blog>javac DecimalToBinaryEg1.java

C:\raji\blog>java DecimalToBinaryEg1

Enter the decimal number: 78

Binary number of decimal number: 1001110

This is the program to convert the decimal number into binary number using user defined code.

2.Using Built-in function:

If you want to use the built-in function to convert the decimal number into binary number, the below program uses the function “toBinaryString()”.

The code is given below.

import java.util.Scanner;

public class DecimalToBinaryEg {

    public static void main(String[] args) {

        Scanner s1 = new Scanner(System.in);

        // Get the Decimal number as input

        System.out.print("Enter the decimal number: ");

        int decimal_no = s1.nextInt();

        // Conversion of decimal to binary using built-in function

        String binary_no = Integer.toBinaryString(decimal_no);

        // Print the Binary representation

        System.out.println("The converted Binary number is: " + binary_no);

        s1.close();

    }

}

While running this program, you get the below output.

C:\raji\blog>javac DecimalToBinaryEg.java

C:\raji\blog>java DecimalToBinaryEg

Enter the decimal number: 67

The converted Binary number is: 1000011

These are the two ways to implement the conversion of decimal number into binary number. Hope this code is useful to you.

Unit conversion program in java

               Science has lot of units. Some of the units are converted into another unit. For example, temperature has Celsius and Fahrenheit. Distance has miles and kilometres.

              Let us create java program to convert these units.

Program implementation:

  • ·       This program reads the choice from the user. Based on the choice,the conversion starts.
  • ·       The input value is read from the command line.
  • ·       If the choice is 1, it converts the Celsius value to Fahrenheit value and print it.
  • ·       If the choice is 2, it makes the Fahrenheit value to Celsius value and display it.
  • ·       If the choice value is 3, the program creates the conversion of kilometers into miles.
  • ·       If the choice is 4, the program converts the miles value  into kilometer value.
  • ·       If choice is any other, it displays the message “Please choose the option between 1 to 4”.

Program:

import java.util.Scanner;

public class convertUnit {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);      

        System.out.println("Unit Converter");

        System.out.println("Choose an option:");

        System.out.println("1.Celsius to Fahrenheit");

        System.out.println("2. Fahrenheit to Celsius");

        System.out.println("3. Kilometers to Miles");

        System.out.println("4. Miles to Kilometers");

         System.out.println("Enter your Choice");

        int choice = scanner.nextInt();

        System.out.println("Enter the value:");

        System.out.println("");

        double value = scanner.nextDouble();

        double cValue;

        if (choice ==1) {

        //Convert Celsius to Fahrenheit

        double F = (value * 9/5) + 32;

        System.out.println("The converted value of Celsius is: "+ F +"Fahrenheit");

        }

        else if (choice == 2){

        //Convert Fahrenheit to Celsius

        double C=(value-32)/1.8;

       System.out.println("The converted value of Fahrenheit is: "+C+"Celsius");

        }

         else if (choice == 3) {

            // Convert Kilometers to Miles

            cValue = value * 0.621371;

            System.out.println("The converted value of Kilometers is:"+cValue+" Miles.");

        }

       else if (choice == 4) {

            // Convert Miles to Kilometers

            cValue = value / 0.621371;

            System.out.println("The converted value of miles:" + cValue + " Kilometers.");

        }

      else {

            System.out.println("Invalid choice. Please select option between 1 to 4.");

        }

         scanner.close();

    }

}

Output:

Compile and run the program to get the output.

C:\raji\blog>javac convertUnit.java

C:\raji\blog>java convertUnit

Unit Converter

Choose an option:

1.Celsius to Fahrenheit

2. Fahrenheit to Celsius

3. Kilometers to Miles

4. Miles to Kilometers

Enter your Choice

1

Enter the value:

98

The converted value of Celsius is: 208.4Fahrenheit

C:\raji\blog>java convertUnit

Unit Converter

Choose an option:

1.Celsius to Fahrenheit

2. Fahrenheit to Celsius

3. Kilometers to Miles

4. Miles to Kilometers

Enter your Choice

2

Enter the value:

200

The converted value of Fahrenheit is: 93.33333333333333Celsius

C:\raji\blog>java convertUnit

Unit Converter

Choose an option:

1.Celsius to Fahrenheit

2. Fahrenheit to Celsius

3. Kilometers to Miles

4. Miles to Kilometers

Enter your Choice

3

Enter the value:

34

The converted value of Kilometers is:21.126614 Miles.

C:\raji\blog>java convertUnit

Unit Converter

Choose an option:

1.Celsius to Fahrenheit

2. Fahrenheit to Celsius

3. Kilometers to Miles

4. Miles to Kilometers

Enter your Choice

4

Enter the value:

56

The converted value of miles:90.12329188198355 Kilometers.

This is the way of implementing unit conversion program in java.Hope this code will useful to you. Keep coding….

Java Swing Application to display the given message

Let us create a simple application to display the message in the text field to a separate screen.

What are the components you need?

  • ·       A frame
  • ·       A Panel
  • ·       Label
  • ·       Text field
  • ·       Submit button.

These the Swing components used in the program.

Let us implement the sample application.

Program implementation:

  • First, include the built-in packages javax.swing,java.awt,java.awt.event.
  • Create a public class with main() function.
  • Design the components as follows.
  • A frame ,A Panel , Label , Text field and a submit button. Let us make objects for each components.
  • Set the frame object’s heading as “Display the message”. Jpanel object p1 is created.
  • Label object is created with the message “Enter the message”. It makes the user to enter the message.
  • TextField object is declared with size of 15.
  • A button object is initialised with button name as “Submit”.
  • Let us make the components into a row. Set the layout as Flow layout.
  • Add the textfield,button and label into the panel.
  • When you enter the message in the text field and click the submit button,it calls this part of the program.
  • This part gets the string into msg variable.
  • It displays the message in a separate window.

Program:

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class SampleApp {

    public static void main(String[] args) {

        JFrame f1 = new JFrame("Display the Message");

        JPanel p1 = new JPanel();

        JLabel l1 = new JLabel("Enter the message:");

        JTextField txtField = new JTextField(15);

        JButton button1 = new JButton("Submit");

        p1.setLayout(new FlowLayout()); // Arranging all components in a row

        p1.add(l1);

        p1.add(txtField);

        p1.add(button1);

       //button event

        button1.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                String msg = txtField.getText();

                JOptionPane.showMessageDialog(f1, "Hi, your message is : " + msg + "!");

            }

        });

        f1.add(p1);

        f1.setSize(250, 150);

        f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        f1.setVisible(true);

    }

}

Here is the output.

 

That’s all. A sample swing application is created here. Hope this code is useful to you.