Search code examples
javaloopsfor-loopnested-loops

Nested for loops and the placement of variables


I am currently attempting to solve a problem where I try to find the smallest triangular sum of terms in a triangular array. (The array I am currently using is a 3x3 triangular array)

  colAmt =1;
  int tempCol = rows;
  int tempSum=0;
  rows = 3;

  for(int t=0;t<rows;t++)
  {

      for(int col = 0; col<colAmt; col++)
      {
          tempCol=0;
          tempSum =0;

          for(int m=t;m<rows;m++)
          {
              System.out.println(m+", "+tempCol);
              tempSum = tempSum + sumTriangle[m][tempCol];

                      tempCol++;
                      if(tempSum<triSum)
                      {
                          triSum = tempSum;
                      }
          }
      }
      colAmt++;
  } 

When I execute the program, the program prints out:

(0, 0)
(1, 1)
(2, 2)
(1, 0)
(2, 1)
(1, 0)
(2, 1)
(2, 0)
(2, 0)
(2, 0)

When it should be printing:

(0, 0)
(1, 1)
(2, 2)
(1, 0)
(2, 1)
(1, 1)
(2, 2)
(2, 0)
(2, 1)
(2, 2)

I'm pretty sure It's a problem with the way I'm handling the tempCol variable, but I'm not sure how to fix it. Any help is appreciated. Thanks!


Solution

  • You can get the numbers you want by replacing

    tempCol=0;
    

    with

    tempCol=col;