do while Loop in Typescript
TypeScript's do-while loop sits at the intersection of while and for, offering a unique twist on iteration. Unlike while, which checks the condition before each execution, and for, which uses a pre-defined counter, do-while always executes its block at least once. Then, it checks the condition, allowing repetition as long as it's true.
Basic do...while loop
The basic structure of a do...while loop is as follows:
The loop will execute the code block first and then check the condition. If the condition is true, the loop will continue; otherwise, it will exit. Here's an example:
This loop ensures the user gets at least one chance to guess the correct number. Even if their initial guess is wrong, the loop body executes first, displaying the guess. Then, the condition checks if it's 5, and the loop repeats if not. This guarantees at least one interaction before considering the provided value.
Counting with do-while
This loop showcases do-while for counting. Unlike a traditional for loop, it initializes the counter and then executes the block before checking the condition. This allows printing the initial value of count (0) before incrementing and checking if it's less than 5.
Looping until user input
This loop utilizes do-while for user input control. Regardless of the initial input, the prompt is displayed at least once. Then, the condition checks if the input is not "n" (ignoring case), continuing the loop if true. This ensures the user always has the opportunity to choose before exiting.
Combining with break statements
This example combines `do-while` with an `if` statement and `break`. While the main loop condition is always true (for demonstration purposes), the `if` block within checks for password length. If valid, it prints a message and `break`s the loop, guaranteeing at least one attempt and early exit upon successful input.
Nesting with other loops
This example shows nested `do-while` with a `for` loop. The outer `do-while` controls the number of rows printed, while the inner `for` loop prints the required number of stars per row. This showcases how `do-while` can handle complex iteration patterns involving multiple loops.
Nested do...while loop
do...while loops can also be nested within other loops or control flow structures. Here's an example with a nested loop that prints a triangle of stars:
This nested do...while loop prints a triangle of stars, and the outer loop controls the number of rows in the triangle.
Conclusion
The do...while loop ensure that the loop body is executed at least once, as the condition is checked after the initial execution. These loops are useful for scenarios where the exact number of iterations is not known beforehand, but it's essential to guarantee the execution of the loop's code block.