# 2-dimensional arrays

• August 9th, 2012, 12:02 AM
johnmerlino
2-dimensional arrays
In this code snippet:

Code :

```public static int[][] pascalTriangle(int n) { int[][] pt = new int[n][]; for (int i = 0; i < n; i++) { pt[i] = new int[i + 1]; pt[i][0] = 1; for (int j = 1; j < i; j++) { pt[i][j] = pt[i - 1][j - 1] + pt[i - 1][j]; } pt[i][i] = 1; } return pt; }```

in the second live, we specify a length for the one dimesnion, but for the second dimension, its just open and close brackets. How is it possible to do that, to be able to declare a two-dimensional array like that without specifying a length? I thought an array had to have an exact length when initialized before you could actually assign items to it.
• August 9th, 2012, 12:31 AM
pbrockway2
Re: 2-dimensional arrays
pt is an array whose members are (or will be) arrays of int values. You can think of it as a 2d array, but it is an array whose elements are themselves arrays.

And when you initialised pt you did specify a length: its length is n. You can try "System.out.println(pt.length);". What you didn't specify - and don't have to - is the length of the arrays which are the elements of pt. It is only when you say:

Code :

`pt[i] = new int[i + 1];`

that you give these so called "inner" arrays a length. And notice that the inner arrays (the elements of the pt array) do not all have to be the same length. In your case they are not all the same length.

A double array in Java differs from, say, a matrix in maths where there is a definite number of elements in each direction. A better mental image might be a page of text. The page consists of an array of lines. And each line consists of an array of characters. But even once you've said how many lines there are, you haven't said how long the lines will be - and they can all be different lengths. Sometimes people borrow the term "ragged" from printed text to describe the corresponding arrays in Java.
• August 9th, 2012, 06:50 AM
Samaras
Re: 2-dimensional arrays
You can also imagine it as a triangular array
• August 9th, 2012, 01:15 PM
johnmerlino
Re: 2-dimensional arrays