Professional Documents
Culture Documents
Syntax:
for (initialization; condition; iteration statement)
{
code to be executed if condition is true
}
The for loop is the most compact form of looping and includes the following three important parts:
1) initialization :
The loop initialization where we initialize our counter to a starting value. The
initialization statement is executed before the loop begins.
2) condition:
The test statement which will test if the given condition is true or not. If condition is true
then code given inside the loop will be executed otherwise loop will come out.
3) iteration statement :
The iteration statement where you can increase or decrease your counter
You can put all the three parts in a single line separated by a semicolon
Example 1:
<html>
<head>
<title>Title of the document</title>
<script language="javascript">
var num,i
document.write("The 1 to 10 numbers are: <br>")
for (i=1;i<=10;i++)
{
document.write(i+" ")
}
</script>
</head>
<body>
</body>
</html>
Output:
Example 2:
Write javascript application for display even and odd numbers from 1 to 10 using for loop
<html><head><title></title>
<script language="javascript">
var num,i
document.write("The even numbers between 1 to 10 are: <br>")
for (i=1;i<=10;i++)
{
if (i%2==0)
{
document.write(i+" ")
}
}
document.write("<br>The odd numbers between 1 to 10 are: <br>")
for (i=1;i<=10;i++)
{
if (i%2==1)
{
document.write(i+" ")
}
}
</script>
</body>
</html>
Output: