The do…while loop can be used to execute a specific block of code at least once
There are mainly two types of loops.
- Entry Controlled loops: In this type of loop, the test condition is tested before entering the loop body. For Loop and While Loops are entry-controlled loops.
- Exit Controlled Loops: In this type of loop the test condition is tested or evaluated at the end of the loop body. Therefore, the loop body will execute at least once, irrespective of whether the test condition is true or false. the do-while loop is exit controlled loop.
Example 1: In this example, we will illustrate the use of a do…while loop
let test = 1;
The main difference between do…while and while loop is that it is guaranteed that do…while loop will run at least once. Whereas, the while loop will not run even once if the given condition is not satisfied
Example 2: In this example, we will try to understand the difference between the two loops
let test = 1;
Explanation: We can see that even if the condition is not satisfied in the do…while loop the code still runs once, but in the case of while loop, first the condition is checked before entering into the loop. Since the condition does not match therefore the while loop is not executed.
Let us compare the while and do…while loop
|It is an exit-controlled loop
|It is an entry-controlled loop.
|The number of iterations will be at least one irrespective of the condition
|The number of iterations depends upon the condition specified
|The block code is controlled at the end
|The block of code is controlled at starting
Note: When we are writing conditions for the loop we should always add a code that terminates the code execution otherwise the loop will always be true and the browser will crash.
- Internet Explorer
Share your thoughts in the comments
Please Login to comment...