Skip to content
Advertisement

Checking to see if a 2d array is jagged

I am finishing up a program but having a bit of trouble with one last aspect.

In this part of the program, I am testing to see if the array is jagged (same number of rows and columns). I want to use a nested for loop to do this but am having trouble with the logic and structure.

For example, the following array is jagged:

JavaScript

And the following array is not:

JavaScript

Can anyone offer guidance on how to do this?

Advertisement

Answer

Start with being clear about what a jagged array is (sticking to 2D arrays as the typical case):

  1. Technically a jagged array is an array of (1D) arrays, each of which can have a different length.
  2. Often what people mean by “jagged array” (including you I think) is an array with (1D) array elements that do vary in length – i.e. “effectively jagged”.
  3. Finally, an array that is technically jagged but has the “same number of rows and columns” is (effectively) a square array.

(Notice that effectively jagged and effectively square arrays are mutually exclusive.)

You do not need nested for loops to check for any of these three conditions:

  • Condition 1 is self-evident by virtue of a int[][] declaration.
  • Conditions 2 and 3 necessitate one for loop – because you do not need to iterate through the array that contains the potentially different-length arrays and the potentially different-length arrays, just iterate through the former and check the lengths of the latter.

Having said this, consider the following IsJagged and IsSquare implementations and demo with respect to conditions 2 and 3:

JavaScript

If you run the demo, you should see the following output:

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