TypeScript – Do While Loop


TypeScript – do…while loop


”;


The do…while loop is similar to the while loop except that the do…while loop doesn’t evaluate the condition for the first time the loop executes. However, the condition is evaluated for the subsequent iterations. In other words, the code block will be executed at least once in a do…while loop.

Syntax

The syntax of do…while loop in TypeScript is as follows –

do {
   //statements 
} while(condition)

In the syntax of do…while loop, do block contains the code block that is executed in each iteration. The while block contains the condition that is checked after the do block executes.

In the above syntax, the condition is a boolean expression that evaluates to either true or false.

Flowchart

The flowchart of the do…while loop looks as follows –

Do While

The flowchart shows that at first the loop control goes to the code block. Once the code block is executed, the condition is checked. If the condition evaluates to true, the loop control again goes to the code block and code block is executed. If the condition evaluates to false, the do…while loop breaks.

Let’s now try an example of do…while loop in TypeScript.

Example: do…while

In the example below, we define a variable n with value 10. Inside the do block, we print the value of n and then decrement it. The while block holds the condition n>=0, which determines if another iteration occurs.

var n:number = 10;
do { 
   console.log(n); 
   n--; 
} while(n>=0); 

On compiling, it will generate following JavaScript code −

var n = 10;
do {
   console.log(n);
   n--;
} while (n >= 0);

The example prints numbers from 0 to 10 in the reverse order.

10 
9 
8 
7 
6 
5 
4 
3 
2 
1 
0
typescript_loops.htm

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *