poonamsharma
poonamsharma

Reputation: 61

2 counters in one for loop?

My output is coming wrong and I realised the reason that I am running "for loop" for "k" a value of "for loop" of j..

Running for loops for "j and k" simultaneously would solve my problem. How to do that?

public void yestimatedvalue() {
    for (int i = 1; i < bmarray.length; i++) {
        double g = 0;
        s = i;
        int p = missingrowcolindex(s);
        System.out.println("p::\t" + p);

        for (int j = 0; j < bmarray[i].length; j++) {
            if (j != p) {
                g = arraybeta[0][p];

                for (int k = 1; k < arraybeta.length; k++) {
                    g = g + ((bmarray[i][j]) * (arraybeta[k][p]));

                }

            }
        }
         System.out.println("g::\t" + g);
    }
}

output::

g:: 23.99999999999998

g:: 4.9999999999999964

g:: 5.999999999999995

g:: 1.0

Upvotes: 5

Views: 16452

Answers (2)

Caffe Latte
Caffe Latte

Reputation: 1743

Answering this question Running for loops for "j and k" simultaneously is:

for(int j=0, k=1; (j < bmarray[i].length && k < arraybeta.length); j++, k++){
  //....
}

Upvotes: 12

AlexR
AlexR

Reputation: 115398

Yes, you can. Java (and all c-like languages) support syntax like this:

for(int i=0, j=5, k=2; i < 10 && j < 50; i++, j+=2, k+=3) {
}

Upvotes: 9

Related Questions