Javascript


Related applications


Search a word:
   



© The scientific sentence. 2010


Looping:




Looping is used when some block of code will be 
exected a number of times, knowing in advance how 
many times the script will be run; or while a 
specified condition is true. We use the loops "for", 
"while", and "Do while".

1. Loop for


FOR
Example:
<body>
<script type="text/javascript">
for (i = 1; i <= 4; i++)
{
document.write(" The number is :  " + i + "<br />");
}
</script>

</body>

The output is:

The number is : 1
The number is : 2
The number is : 3
The number is : 4

2. While:


<body>
<script type="text/javascript">
i=3;
while (i<=7)
{
document.write(" The number is :  " + i + "<br />");
i=i+1;
}
</script>
</body>

The variable "i" is equal to 3. While "i" is less than, or equal to, 
7, the loop will continue to run; "i" is increased by 1 each time 
the loop runs.

The output is:

The number is : 3
The number is : 4
The number is : 5
The number is : 6
The number is : 7

3. Do while:



<body>
<script type="text/javascript">
var i = 3;
do 
{
document.write(" The number is :  " + i + "<br />");
i++;
}
while (i<1);
</script>
</body>

The do...while loop will execute the block of code 
once. If the condition in while (condition) statement 
is true, the loop will continue, otherwise, it stops leaving 
behind the test first result even if the condition is false.

The output is:

The number is : 3

4. break and continue statement:


Inside a loop, we use the break statement 
to stop the loop, and continue statement 
to break the current loop and continue with 
the next value.

Example

<body>
<script type="text/javascript">
var j=3;
for (j=3;j<=7;j++)
{
if (j==5)
{
break;
}
document.write("<br />The double is :" + j*2 + "<br />");
}

var i=3;
for (i=3;i<=7;i++)
{
if (i==5)
{
continue;
}
document.write("<br />The double of " + i + " is :" + i*2 + "<br />");
}
</script>
</body>

The outputs are:

The double is :6
The double is :8
and:

The double of 3 is :6
The double of 4 is :8
The double of 6 is :12
The double of 7 is :14
  
Google
Web
ScientificSentence
 




chimie labs
|
scientific sentence
|
java
|
php
|
green cat
|
contact
|


© Scientificsentence 2009. All rights reserved.