Saturday, December 26, 2015

Java Program to add two Matrix

Java Program to add two Matrix:


package javaapplication22;

import java.util.Scanner;


public class AddTwoMatrix {
    public static void main(String[] args) {
       Scanner s = new Scanner(System.in);

       System.out.print("Enter number of rows: ");
       int rows = s.nextInt();

       System.out.print("Enter number of columns: ");
       int cols = s.nextInt();

       int[][] a = new int[rows][cols];
       int[][] b = new int[rows][cols];

       System.out.println("Enter the first matrix");
       for (int i = 0; i < rows; i++) {
           for (int j = 0; j < cols; j++) {
               a[i][j] = s.nextInt();
           }
       }
       System.out.println("Enter the second matrix");
       for (int i = 0; i < rows; i++) {
           for (int j = 0; j < cols; j++) {
               b[i][j] = s.nextInt();
           }
       }
       int[][] c = new int[rows][cols];
       for (int i = 0; i < rows; i++) {
           for (int j = 0; j < cols; j++) {
               c[i][j] = a[i][j] + b[i][j];
           }
       }
       System.out.println("The sum of the two matrices =");
       for (int i = 0; i < rows; i++) {
           for (int j = 0; j < cols; j++) {
               System.out.print(c[i][j] + " ");
           }
           System.out.println();
       }
   }
}

Output:
Enter number of rows: 2
Enter number of columns: 2
Enter the first matrix
1 2
3 4
Enter the second matrix
1 4
3 5
The sum of the two matrices =
2 6 
6 9 

Related Posts:

  • String Length in java String Length in java: The length of the String is the actual number of character that contains in it.To get this value,call the length() method as … Read More
  • Overloading Constructor: Overloading Constructor: package overloadingconstrucror; public class Box {     double width;     double height;     d… Read More
  • Increment And Decrement Operator Increment and Decrement Operator: package javaapplication16; public class IncrementAndDecrementOPeratorDemo {     public static void mai… Read More
  • Java break statement: Java break statement: package javaapplication27; public class BreakDemo {     public static void main(String[] args) {     &nbs… Read More
  • Stack in java: Stack in java: package javaapplication27; import java.util.Stack; public class TestStack {         public static void main(Str… Read More

0 comments:

Post a Comment