Skip to content
Advertisement

Exception in thread main Java

This is my program to print natural numbers from 1 to N^2 in a clockwise spiral. I’m getting the following error

JavaScript

This is my program

JavaScript

The code works fine for N=2 but starts giving this error for N=3,4 etc. If N=3, the greatest value of arr[i][c2] will be arr[2][2] which falls in the range of a 3×3 matrix. Could someone explain why I’m getting this error then?

Advertisement

Answer

Increment/decrement r1, c2, r2, and c1 appropriately after their corresponding for loops rather than at the end of the while loop:

JavaScript

Example Usage 1:

JavaScript

Example Usage 2:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement