manis
manis

Reputation: 729

Why does this result in a infinite loop?

I am trying to program a method that will use Gauss Elimination on a matrix (2 dimensional array), and I'm trying to debug my method and I've encountered this problem

public int Gauss() {
    int i = 1;
    int j = 1;
    int pivotCol = 0;
    while (pivotCol == 0 && j <= cols())
        if (i == rows()){
            j ++;
            i = 1;
        }
        if (get(i,j) == 1.0){
            pivotCol = j;
        } else {
            i ++;
        }
    return pivotCol;
}

This is not the final method, but for some reason, this loop never ceases, why?

Upvotes: 0

Views: 107

Answers (2)

Ben
Ben

Reputation: 1177

while (pivotCol == 0 && j <= cols()) {
...
}

You forgot the brackets, so the while is only working with the if statement and therefore its running infinite.

Upvotes: 11

Andrew Logvinov
Andrew Logvinov

Reputation: 21851

I guess the problem is that your while loop doesn't have curly braces, e.g. it's effectively as follows:

while (pivotCol == 0 && j <= cols()) {
  if (i == rows()){
    j++;
    i = 1;
  }
}

If i != rows() this will never terminate.

Upvotes: 7

Related Questions