When do I have to use a while or a do while? [closed]

0

Good I wanted to know when I realize when I have to use while or do while to make a program, because I've seen people who say: "no I would not do this with a for, you can use the while or do while".

    
asked by computer96 27.11.2018 в 17:37
source

1 answer

6

The while loop and the for loop in Java are interchangeable, it is the loop do .. while the one is a bit different, since the first two check the condition before to execute its block code, while the last one does after run it.

Since Java and Javascript syntax are practically the same for this scenario, let me show the differences with an executable example in the browser:

let contador= 0;

do {
  console.log('El contador vale', contador);
  contador++;
} while (contador<0);

console.log('El contador vale al salir', contador);

contador = 0;
while (contador<0) {
  console.log('El contador vale', contador);
  contador++;
}

console.log('El contador vale al salir', contador);

for (contador=0; contador<0; contador++) {
  console.log('El contador vale', contador);
  contador++;
}

console.log('El contador vale al salir', contador);

  

Related question: for / for each loop

    
answered by 27.11.2018 / 17:50
source