Adscend

Click Here



Click Here

Monday

For Loop

For Loop

For loop executes a certain condition as many times as you want.

Syntax
for(intial value; condition; increment)
{
// set of statements that will be executed
}
All the three parameters are separated by semicolon ";".
Loop is used to execute the same set of statements with a specified number of times(until a condition is satisfied) in incremental or detrimental way.


Example: 1

<script type="text/javascript">
var i=0
for(i=0;i<=5;i++)
{
document.write(i+ "<br />");
}
</script>

Output

0
1
2
3
4
5

Note: When "i<=5" executes, then condition remain true and loop terminates when "i=6". "i<=5" says "i" is less than or equal to 5”.


Example: 2

<script type="text/javascript">
var i=0;
var sum=0;
for(i=1; i<5; i++)
{
sum = sum+i;
}
document.write("The sum of 1 through 4 is: " +sum);
</script>

Output

The sum of 1 through 4 is: 10



No comments:

Post a Comment