Sum of two dimensional array:-
This program will explain how to add array which is two dimensional.You first have to know what is two dimensional array.Two Dimensional Array- Two dimensional array those array which is consists of elements of 2-d type. Basically 2-d means rows and columns.2-d dimensional array. It's syntax can be declared as given below:
data_type array_name[size1][size2];
A way to initialize the two dimensional array at the time of declaration is given below:
int arr[4][3]={{1,2,3}, {2,3,4}, {3,4,5}, {4,5,6}};Example to declare 2-d dimensional array is:
int m[][]=new int[4][6];
Now this is a 2-d array which is initialize with the values of 4 and 6. 4 means it has the values of 4 rows and 6 means it has the values of 6 columns.
Logic behind addition:- The logic behind addition is that it add the elements the array according to the indices. Suppose i have one array of two rows and two columns,while other array of two rows and 3 columns. Then the values of indices are added i.e. first element of first column of first array gets added with the first element of first column of second array.
Program of sum of two dimensional array in java:
import java.util.Scanner;
public class two_d_arr_sum
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int m[][]=new int[50][60];
int n[][]=new int[60][60];
int o[][]=new int[70][70];
int i,j,r,c;
System.out.println("ENTER ROWS AND COLUMNS OF FIRST MATRIX");
r=sc.nextInt();
c=sc.nextInt();
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
m[i][j]=sc.nextInt();
}
}
System.out.println("YOUR FIRST MATRIX IS");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
System.out.print("\t"+m[i][j]);
}
System.out.println();
}
System.out.println("ENTER ROWS AND COLUMNS OF SECOND MATRIX");
r=sc.nextInt();
c=sc.nextInt();
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
n[i][j]=sc.nextInt();
}
}
System.out.println("YOUR SECOND MATRIX IS");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
System.out.print("\t"+n[i][j]);
}
System.out.println();
}
System.out.println("THE SUM OF TWO MATRICES IS:");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
o[i][j]=m[i][j]+n[i][j];
System.out.print("\t"+o[i][j]);
}
System.out.println();
}
}
}
In above program of sum of two dimensional array, what happening is that first it will ask the user to enter the rows and columns of first matrix i.e. first array. After entering the first array rows and columns, you have to enter the values for that matrix.After it will show your entered matrix. After pressing enter,it will ask the user to enter rows and columns of second matrix. After enter rows and columns you have to provide the values to second matrix as that of first matrix. After entering values when you press enter it will print the sum matrix representing the sum of two matrices is:
The output of above program is some like this: