Nested for loop in java. Am I allowed to declare a variable in the outer and increment it in the inner?

So you have a matrix (Multi dimensional array) with number of ‘a’ rows and ‘b’ columns
and you want to turn this matrix into one dimensional array.

   int l = 0
   for(int i=0; i<a; i++){
     for(int j=0; j<b ; j++){
      narray[l]=oldarray[i][j];
      l++;
     }
   }

this code is valid in java.. but look at the inner for loop.. just the first line next to the for loop will be execute so the variable 'l' will remain 0 until the inner loop will finish the loop.. so in this case you just set the first element of the new array..

so you need to change the code..
the new array length will be a*b (rows*columns)

  int l = 0
  for(int i=0; i<a; i++)
  {
      for(int j=0; j<b ; j++)
      {
         narray[l]=oldarray[i][j];
         l++;
      }
   }

Leave a Comment