package com.programming.java;
public class MultiDimensionalArrays {
public static void main(String[] args) {
//2D
int[][] intArr= {{1,2,3},{4,5,6},{7,8,9}};
for(int i=0;i<intArr.length;i++)
{
for(int j=0;j<intArr.length;j++)
{
System.out.print(intArr[i][j]+" ");
}
System.out.println();
}
int[][] a= {{1,2,3},{4,5,6}};
int[][] b= {{1,2,3},{4,5,6}};
int[][] c=new int[2][3];
for(int i=0;i<a.length;i++) {
for(int j=0;i<b.length;j++)
{
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();
}
System.out.println();
}
}
Instructor
Yogesh Chawla Replied on 06/12/2021
Hi Shinia, Run this. I have written some comments. If you could not understand anything, Please let me know:
package com.programming.module7;
public class MultiDimensionalArrays {
public static void main(String[] args) {
// 2D
int[][] intArr = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for (int i = 0; i < intArr.length; i++) {
for (int j = 0; j < intArr.length; j++) {
//individually printing row and column of each array index
System.out.print(intArr[i][j] + " ");
}
//next line
System.out.println();
}
System.out.println();
int[][] a = {{1, 2, 3}, {4, 5, 6}};
int[][] b = {{1, 2, 3}, {4, 5, 6}};
//another matrix to store the sum of two matrices
int[][] c = new int[2][3];
//adding and printing addition of 2 matrices
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
// for example c[0][0] is a[0][0] + b[0][0] which is 2
// then a[0][1] + b[0][1] which is 4, so on and so forth
c[i][j] = a[i][j] + b[i][j];
System.out.print(c[i][j] + " ");
}
System.out.println();
}
System.out.println();
}
}
why does it show exception:Index 3 out of bounds for length 3
and how to correct it?
Also i want to sum up the whole matric of both a and b and not just till index 2 of both of the 2D arrays...how to do that?
There are 2 rows and 3 columns in our array and if we run the above code which I have pasted, we don't get any error.