user2785277
user2785277

Reputation: 345

Nested while loops stop after first iteration?

I'm trying to compare values using a table "charms" but my outer 3 loops will only register the first iteration; only the innermost loop compares all values.

while (m < 17) {
        while (n < 17) {
            while (o < 17) {
                while (p < 17) {
                    number = (Math.pow(w, charms[m]))
                            * (Math.pow(x, charms[n]))
                            * (Math.pow(y, charms[o]))
                            * (Math.pow(z, charms[p]));
                    if (Math.abs(cons - number) < Math.abs(cons - closest)) {
                        closest = number;
                        a = charms[m];
                        b = charms[n];
                        c = charms[o];
                        d = charms[p];
                    }
                    p++;
                }
                o++;
            }
            n++;
        }
        m++;
    }

Upvotes: 0

Views: 1211

Answers (2)

ajb
ajb

Reputation: 31699

It would be helpful to know what the initial values of m, n, o, and p are, and what the values of charms are. But there's a simple reason this won't work: Say m, n, o, and p are all set to 1 before the loop. Then the inner loop executes and exits when p is 17. So then you increment o and start that loop over--but what is p? It's still 17! It's never set back down to 1 or whatever. So none of the code in the innermost loop ever ever ever executes again.

At the very least, you need to reset each variable before you loop on it:

 while (m < 17) {
    n = 1;  // or whatever, you haven't told us what it's supposed to start at
    while (n < 17) {
        o = 1;
        while (o < 17) {
            p = 1;
            while (p < 17) {

or even better, use for loops which put the initialize, test, and increment logic all in one place.

Upvotes: 0

Jim Rhodes
Jim Rhodes

Reputation: 5085

First of all, you do not show how you initialize m, n, o and p. Secondly, you are not resetting the counters at any point. Once you go through the most inner loop once, you will never go through it again since p will be greater than or equal to 17 after that. Then once o reaches 17, you will never go into that loop again and so on.

Upvotes: 4

Related Questions