Home > Net >  do-while loop is not behaving as expected
do-while loop is not behaving as expected

Time:11-12

Feel dumb, but having coded for 10 years, haven't used a do-while loop in the last 9. For the life of me, I cannot figure out why this is returning 1 instead of

 const getNextEventCountTest = () => {

        
        let sum = 0;
        let q = 0;

        do {
            sum = sum   0.5
        }
        while (sum < 4){
         
            q = q   1;
        }

        return q;
  };

do-while is a good here, since I want to always run the first code block but only conditionally increment q.

but this:

console.log(getNextEventCountTest()); => 1

feeling dumb but dunno lol.

whereas this has the right behavior:

const getNextEventCountTest = () => {
  
        let sum = 0;
        let q = 0;

        // this is desired behavior:
        while (sum < 4){
            sum = sum   0.5
            if(sum < 4){
               q = q   1;
            }
        }

        return q;
  };

CodePudding user response:

This is because your code executes like do { ... } while(condition); { ... }. Notice the added semicolon - the second {} block executes once.

CodePudding user response:

Your syntax is wrong regarding do while loop. Use this instead

do {
  //Your code that is to be executed
}
while(/* condition */);

I have improved the code for you;

const getNextEventCountTest = () => {
  let sum = 0, q = 0;

  // works only when sum and q are defined as an integer
  do{
     sum  = 0.5
     if(sum < 4) q  ;
  }
  while(sum < 4)
  return q;
}

Then, it will work as expected. Bye, have a great day!

  • Related