A loop will execute the same block of code when a condition is true or a specified number of times.
- for loop
- for..in loop
- while loop
- do..while loop
In the above code:
- i=1 - Loop start from 1 (one)
- i < =5 - It will execute up to 5 times (1 - 5)
- i++ - Each time increment 1 value, that is i = i+1
A while loop runs the same code block until the specified condition is true. It enables you to test a condition and keep on looping when it meets the specified condition.
The do..while loop runs almost identically to a while loop, with only one key difference. It will executes a block of code once and then checks the specified condition.
There are many situations when you want the code in the while loop to run at least once, regardless of whether the condition in the while statement evaluates to true or false. In these situations you can use do..while loop
Difference between while loop and do..while loop
The difference between a while loop and a do..while loop is that the do..while loop execute the code block at least once whether or not the condition is met.
The program first set myVal as false (var myVal=false;) . Then the program encounters a while loop. The while loop won't execute because the specified condition is false (myVal=false;). Then the program encounter a do..while loop. Here you can see even myVal is false the code block will execute once and exit from the do..while loop because the specified condition is false(myVal=false;)
If you have an expression that always evaluates to true , that is your code gets stuck in the loop "forever". These types of loop is called infinite loop.
This loop will run forever because there is no condition is specified in the loop statement.
While you are in a loop and you want to exit from the loop when a specified condition is met, in such situations you can use break statement. The break statement exits from the loop body immediately and forcing execution to continue with the next statement after the loop
In the above code , the loop will execute only 1 time because when the loop will meet the condition i==2 , then the break statement will terminate the loop and comes out of the loop body
When the loop meet the continue statement then the loop control goes to the starting point of the loop and skip the remaining code block.
In the output you can see the 2 is missing because when it meets the condition if (i==2) inside the loop, it will continue to the starting point of the loop and skip the remaining code block.