TypeScript Indefinite Loops

In a programming language, loops are the sequence of instructions which continually repeated until a specific condition is not found. It makes the code compact. We can mostly use it with the array. Below is the general structure of the loop statement:

TypeScript Indefinite Loops

We can classify the loops into two types:

TypeScript Indefinite Loops
  1. Indefinite
  2. Definite

Indefinite Loop

In Indefinite loops, the number of iterations is not known before beginning the execution of the block of statements. There are two indefinite loops:

  1. while loop
  2. do-while loop

while loop

The TypeScript while loop iterates the elements for the infinite number of times. It executes the instruction repeatedly until the specified condition evaluates to true. We can use it when the number of iteration is not known. The while loop syntax is given below.

Syntax
snippet
while (condition)  
{  
    //code to be executed  
}
TypeScript Indefinite Loops

The explanation of while loop syntax is:

While loop starts the execution with checking the condition. If the condition evaluates to true, the loop body statement gets executed. Otherwise, the first statement following the loop gets executed. If the condition becomes false, the loops get terminated, which ends the life-cycle of the loops.

Example
snippet
let num = 4;
let factorial = 1;

while(num >=1) {
   factorial = factorial * num;
   num--;
}
console.log("The factorial of the given number is: "+factorial);
TypeScript Indefinite Loops

do-while loop

The TypeScript do-while loop iterates the elements for the infinite number of times similar to the while loop. But there is one difference from while loop, i.e., it gets executed at least once whether the condition is true or false. It is recommended to use do-while when the number of iteration is not fixed, and you have to execute the loop at least once. The do-while loop syntax is given below.

Syntax
snippet
do{  
    //code to be executed  
}while (condition);
TypeScript Indefinite Loops

The explanation of do-while loop syntax is:

The do-while loop starts executing the statement without checking any condition for the first time. After the execution of the statement and update of the variable value, it starts evaluating the condition. If the condition is true, the next iteration of the loop starts execution. If the condition becomes false, the loops get terminated, which ends the life-cycle of the loops.

Example
snippet
let n = 10;

do { 
    console.log(n); 
    n++; 
 } while(n<=15);
TypeScript Indefinite Loops
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +