Write a Java program to add two matrices of the same size


Introduction

In this demo I have used NetBeans IDE 8.2 for debugging purpose. But you can use any java programming language compiler as per your availability..


techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

  1. import java.util.Scanner;
  2. public class Javaexcercise {
  3.  
  4. public static void main(String args[])
  5. {
  6. int a, b, c, d;
  7. Scanner in = new Scanner(System.in);
  8.  
  9. System.out.println("Enter number of rows of matrix");
  10. a = in.nextInt();
  11. System.out.println("Enter number of columns of matrix");
  12. b = in.nextInt();
  13.  
  14. int array1[][] = new int[a][b];
  15. int array2[][] = new int[a][b];
  16. int sum[][] = new int[a][b];
  17.  
  18. System.out.println("Enter elements of first matrix");
  19.  
  20. for ( c = 0 ; c < a ; c++ )
  21. for ( d = 0 ; d < b ; d++ )
  22. array1[c][d] = in.nextInt();
  23.  
  24. System.out.println("Enter the elements of second matrix");
  25.  
  26. for ( c = 0 ; c < a ; c++ )
  27. for ( d = 0 ; d < b ; d++ )
  28. array2[c][d] = in.nextInt();
  29.  
  30. for ( c = 0 ; c < a ; c++ )
  31. for ( d = 0 ; d < b ; d++ )
  32. sum[c][d] = array1[c][d] + array2[c][d];
  33.  
  34. System.out.println("Sum of the two matrices:");
  35.  
  36. for ( c = 0 ; c < a ; c++ )
  37. {
  38. for ( d = 0 ; d < b ; d++ )
  39. System.out.print(sum[c][d]+"\t");
  40.  
  41. System.out.println();
  42. }
  43. }
  44. }

Result

java techstudy.org

     





Related Topics




Popular Posts