Sunday, 1 April 2018

Looping In javaScript

Loops are used to execute a set of statements repeatedly until a particular condition is satisfied
The basic purpose of loop is to execute set of statements until condition becomes false and same code repeated again and again.

Advantage
It is used to reduce length of Code
It takes less memory space.
Types of Loops
There are three types of loop available in javaScript
·         while loop
·         for loop
·         do-while
  While loop
In while loop  First check the condition if condition is true then the control goes inside the loop body and  print the output , It will repeated again and again until condition becomes false. If condition becomes false control goes outside the body and loop is terminated
Syntax:
assignment;
while(condition){    
Statements;   
………….
Increment/decrement (++,--)

Example:
  <script>  
  var i=1;  
  while (i<=5)  {  
  document.write(i + "<br/>");  
  i++;  }  
  </script> 
Output:
1
2
3
4
5
Note: If while loop condition never false then loop becomes infinite loop

do-while
First print output then checks the condition. Since condition is checked later, the body statements will execute at least once
Syntax:
assignment;
do
{    
Statements;   
………….
Increment/decrement(++,--)
      }
    while(condition); 

Example:
  <script>  
  var i=1;  
  do{  
  document.write(i + "<br/>");  
   i++;
    }  
  while (i<=5);  
  </script> 
Output:
1
2
3
4
5

For loop
for loop is used to iterate a program several times and execute the code repeatedly.
We can initialize variable, check condition and increment/decrement value.
Syntax:
      for(initialization; condition; increment/decrement)
    {    
      //Statement
      }    
Example:
  <script>  
  for (i=1; i<=5; i++)  {  
  document.write(i + "<br/>")  }  
  </script>  
Output:
1
2
3
4
5

Break
break is used to break loop or switch statement.
Syntax:
statement;      
break;  
Example:
<script>
     for(int i=1;i<=5;i++){     
            if(i==4){   
               
                break;     
            }     
   document.write(i + "<br/>")  
        }   
</script>    
Output:
1
2
3

Continue
continue statement is used to continue loop.
Syntax:
Statement;
continue;   
Example:
<script>
     for(int i=1;i<=5;i++){     
            if(i==3){   
               
                continue;     
            }     
  document.write(i + "<br/>")  
        }   
</script>    
Output:
1
2
4
5



1 comment:

  1. Python is an open-source, high level, interpreted programming language which offers great opportunities for object-oriented programming. Choosing a python training program from Red Prism Group, which is best training institute for python in noida.

    ReplyDelete

apply function in R

1) apply function: It takes 3 arguments matrix,margin and function.. Example: m<-matrix(c(1,2,3,4),nrow=2,ncol=2) m #1 indicates it is ap...