JavaScript Control Statements (Iterative Statements)

Control Statements decide according to the condition whether a statement should be executed or not. In the previous post, we saw conditional statements, but we can see about Iterative statements in this article.

This post is to give a basic introduction to control statements in JavaScript. At the end of this article, you will clearly understand the usage of iterative statements.

Let’s understand them with the examples:

  1. Loop/Iterative Statements: while,  do-while,  for loop

WHILE Loop

The syntax for while loop in javascript.

while(condition){
// logic which is to be executed
}

while loop logic will execute only if the condition is true otherwise, it won’t enter the loop.

example:

<html>
 <head> 
 <title> while loop</title>
 </head>
 <script language="javascript" type="text/javascript">
 var n = parseInt(window.prompt("Enter a Number"));
 var r , sum=0;
 var m =n;
 
 while(n > 0)
 {
   r= n % 10;
   sum= sum+(r*r*r);
   n=parseInt(n/10); //here n/10 float-> convert to int
 }
 document.writeln("The sum is " +sum); 
 if(sum == m)
   alert("The num is Amstrong" +m);
 else
   alert("The num is Not a Amstrong " +m);
 </script>
 <body>
</html>

DO-WHILE Loop

The syntax for do-while loop in javascript.

do{
//logic to be executed
}while(condition);

do-while logic will be executed at least once after executing once it will check the condition and according to the condition the loop proceeds, i.e until the condition follows the loop executes and fails to execute if the condition becomes false.

example:

<!-- finding the Reverse of a number -->
<html>
<head> 
 <title> do-while demo </title>
</head>
 <script language="javascript" type="text/javascript"> 
 var n = parseInt(window.prompt("Enter a Number"));
 var r , sum=0;
 do
 {
  r= n % 10;
  sum= sum * 10 +r;
  n=parseInt(n/10); //here n/10 float-> convert to int
 }while(n!=0);

 window.alert("The reverse num is " +sum);
 </script>
 <body>
</html>

FOR Loop

The syntax of for loop in javascript.

for(statement1;statement=2;statement3){
//logic
}
  • statement1 is the initialization statement where we give the initial value to the variable.
  • statement2 is the condition statement where we check the condition if it is true we proceed and execute if it is false we won’t execute
  • statement3 is an increment/decrement statement where we change the value of variable for the free flow of execution

example:

<!-- Prime number or NOt-->
<html>
<head> 
 <title> for loop </title>
</head>
 <script language="javascript" type="text/javascript">
 var n = parseInt(window.prompt("Enter a Number"));
 var flag=true; 
 for(var i=2 ; i <= parseInt(n/2); i++)
 {
  if (n % i == 0)
  {
   flag=false;
   break;
  }
 }
 if(flag==true)
   window.alert("The number is Prime "+n);
 else
   window.alert("The number is Not Prime "+n);
 </script>
 <body>
</html>

 

Leave a Reply

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