1

I have this code below as I saw from textbook

public static int[][] Pascal(int N) {

    int[][] result = new int[N][];      // Build a grid with specific number of rolls

    for (int i = 0; i < N; i += 1) {

        result[i] = new int[i + 1];       // Build an empty row with length
        result[i][0] = result[i][i] = 1;  

        for (int j = 1; j < i; j += 1) {
            result[i][j] = result[i - 1][j - 1] + result[i - 1][j];
        }
    }
    return result;
}

I have no question for how this Pascal triangle is achieved, all very clear.

However, I did learned before that to create an Array, length must be given, for example, int[] A = int[]; will give me Error It has to be int[] A = int[N]; or int[] A = int[]{1,2,3,etc.};

So when we create the array grid int[][] result = new int[N][]; How is it allow me to only specify the number of rows, but leave the length of each row with blank?

I did noticed that the length of each roll was defined later at result[i] = new int[i + 1];, I still don't understand why this grid is allowed to be initiated.

Thanks!

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
jxie0755
  • 1,682
  • 1
  • 16
  • 35
  • 2
    Possible duplicate of [Java Jagged Array](https://stackoverflow.com/questions/10271540/java-jagged-array) – Logan Feb 01 '19 at 15:46
  • 2
    As far as I understand with int[][] result = new int[N][] you simply define a one-dimensional array with N elements. Each of these elements is of type int[] and has to be defined separately. And they can all have different lengths. – mayamar Feb 01 '19 at 15:50
  • @mayamar That makes sense – jxie0755 Feb 01 '19 at 15:51
  • 1
    Think of it like an array of objects: Object[] = new Object[]. There the elements have also defined separately. Just here these objects are arrays too. – mayamar Feb 01 '19 at 15:52
  • @mayamar I see what you mean. I've only created one Array. And stated that this Array will contain array types. So inside this Array, I made a lot of `int[] element;` statements. – jxie0755 Feb 01 '19 at 15:57
  • @mayamar My addtional question: why is it `int[N][]` instead of `int[][N]`?? It seems like I claimed an `[]` of `int[]`, so the length of the grid should be in the second bracket??? – jxie0755 Feb 01 '19 at 16:02
  • I've rolled back your last edit. Please ask one and only one question per question. – Mark Rotteveel Feb 01 '19 at 18:21

0 Answers0