import java.util.*;
class wavePrint {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int arr[][] = new int[n][n];
int right = n - 1, left = 0, dir = 1, count = n*n, i, j;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
arr[i][j] = sc.nextInt();
}
}
while (left <= right) {
if (count > 0) {
if (dir == 1) {
for (i = 0; i <= n - 1; i++) {
System.out.print(arr[i][left] + " ");
count--;
}
dir = 2;
left++;
}
if (dir == 2) {
for (i = n - 1; i >= 0; i--) {
System.out.print(arr[i][left] + " ");
count--;
}
dir = 1;
left++;
}
}
}
}
}
Showing this error :
1 1 1 2 2 2 3 3 3 Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at wavePrint.main(wavePrint.java:26)