Any "Java-ians" here?
[Challenge]
Difficulty Level: Medium
WAP in Java to perform matric addition
Ex:-
1
3
-2
0
2
4
5
1
[Ignore Spaces in latex cod.e]
Hint: Simply add same index elements of both the matric.
Answers
Solution:
The given program is written in Java.
import java.util.*;
public class MatrixAddition{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int rows,cols,i,j;
System.out.print("Enter the number of rows: ");
rows=sc.nextInt();
System.out.print("Enter the number of columns: ");
cols=sc.nextInt();
int a[][]=new int[rows][cols];
int b[][]=new int[rows][cols];
int c[][]=new int[rows][cols];
System.out.println("Enter elements in first matrix...");
for(i=0;i<rows;i++){
for(j=0;j<cols;j++){
System.out.printf("a[%d][%d] >> ",i,j);
a[i][j]=c[i][j]=sc.nextInt();
}
}
System.out.println("\nEnter the elements in second matrix...");
for(i=0;i<rows;i++){
for(j=0;j<cols;j++){
System.out.printf("a[%d][%d] >> ",i,j);
b[i][j]=sc.nextInt();
c[i][j]+=b[i][j];
}
}
System.out.println("\n\nMatrix a[][]:");
displayMatrix(a);
System.out.println("\nMatrix b[][]:");
displayMatrix(b);
System.out.println("\nTheir sum in Third Matrix:");
displayMatrix(c);
}
static void displayMatrix(int a[][]){
for(int x[]:a){
for(int y:x)
System.out.print(y+" ");
System.out.println();
}
}
}
Logic:
- Logic is very simple, just add the elements of both the matrix.
See the attachment for output.
Answer:
Program:-
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
int a[][]=new int[2][2];
int b[][]=new int[2][2];
int c[][]=new int[2][2];
System.out.println("Enter the elements of 1st matrix");
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
a[i][j]=in.nextInt();
}
}
System.out.println("The first matrix:");
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println();
}
System.out.println("Enter the elements ot 2nd matrix");
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
b[i][j]=in.nextInt();
}
}
System.out.println("The second matrix:");
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
System.out.print(b[i][j]+" ");
}
System.out.println();
}
System.out.println("New matrix:");
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();
}
in.close();
}
}