Search code examples
javaarraysjagged-arrays

Jagged array weird behaviour


Here is my jagged array which works perfectly fine during initialization:

   int a[][]=new int[5][];

   for(int i=0;i<5;i++)
    {
   for(int j=0;j<=i;j++)
      {
       a[i]=new int[i+1];
       a[i][j]=j+1;
       System.out.print(a[i][j]);
      }
       System.out.println("");
   }

Gives me desired output :

1
12
123
1234
12345

But printing the same Array with loop just gives absurd output:

  for(int i=0;i<5;i++)
       {
       for(int j=0;j<=i;j++)
         {
          System.out.print(a[i][j]);
         }
          System.out.println("");
       }

Gives:

1
02
003
0004
00005

I cannot draw any conclusion. What's wrong with the code?


Solution

  • You are creating a new array in a[i] for each j during the initialization, and so erasing the previous value.
    Here is the correction:

    int a[][]=new int[5][];
    
    for(int i=0;i<5;i++)
    {
      a[i]=new int[i+1];
      for(int j=0;j<=i;j++)
      {
        a[i][j]=j+1;
        System.out.print(a[i][j]);
      }
      System.out.println("");
    }
    

    As said in the comments, this error is trivial to solve with a debugger. It's time to learn how to use it ;)