Home »
Java Programs »
Core Java Example Programs
Java program to addition of one dimensional and two dimensional arrays
In this java program, we are going to learn how to find addition of one dimensional and two dimensional arrays?
Submitted by Preeti Jain, on March 11, 2018
There are two programs: addition of two one dimensional arrays and addition of two two dimensional arrays.
Addition of two one dimensional arrays in Java
class AddTwoArrayClass{
public static void main(String[] args){
// Declaration and initialization of array
int a[] = {1,2,3,4,5};
int b[] = {6,7,8,9,10};
// Instantiation of third array to store results
int c[] = new int[5];
for(int i=0; i<5; ++i){
// add two array and result store in third array
c[i] = a[i] + b[i];
//Display results
System.out.println("Enter sum of "+i +"index" +" " + c[i]);
}
}
}
Output
D:\Java Articles>java AddTwoArrayClass
Enter sum of 0index 7
Enter sum of 1index 9
Enter sum of 2index 11
Enter sum of 3index 13
Enter sum of 4index 15
Addition of two two dimensional arrays in Java
class AddTwoArrayOf2DClass{
public static void main(String[] args){
// Declaration and initialization of 2D array
int a[][] = {{1,2,3},{4,5,6}};
int b[][] = {{7,8,9},{10,11,12}};
// Instantiation of third array to store results
int c[][] = new int[2][3];
for(int i=0; i<2; ++i){
for(int j=0; j<3; ++j){
// add two array and result store in third array
c[i][j] = a[i][j] + b[i][j];
System.out.println("Enter sum of "+i + " " + j +"index" +" " + c[i][j]);
}
}
}
}
Output
D:\Java Articles>java AddTwoArrayOf2DClass
Enter sum of 0 0index 8
Enter sum of 0 1index 10
Enter sum of 0 2index 12
Enter sum of 1 0index 14
Enter sum of 1 1index 16
Enter sum of 1 2index 18
Core Java Example Programs »