Friday 8 January 2021

Java Script ForLoop Example

 



JAVASCRIPT FORLOOP EXAMPLES
Example 1:  Simple ForLoop
<script>
 /*
Syntax:
for(intializ;conditional; increment / decrement)
{  
coding
*/
for(i=1;i<=5;i++)
{
document.write(i);
}
</script>

Output : 12345


Example 2: ForLoop with Space

<script>
        for(i=1;i<=5;i++)
{
document.write(i+" ");
}
</script>
Output: 1 2 3 4 5


Example 3: Multiple Space Using ForLoop

<script>
        for(i=1;i<=5;i++)
{
document.write(i+" &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
}
</script>
Output: 1     2     3    4     5


Example 4: Print Data in Next Line Using ForLoop

<script>
        for(i=1;i<=5;i++)
{
document.write(i+"<br>");
}
</script>

Output:
1
2
3
4
5


Example 5: ForLoop with Color Formatting

<script>

for(i=1; i<=10; i++)
{
document.write("<font color=red>Number Is:<font><font color=blue>"+i+"</font><br>");
}

</script>



Example 6: star * Pyramid Printing Using ForLoop

<script>
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
document.write("*  ");
}
document.write("<br>");
}
</script>

Output:
*
* *
* * *
* * * * 
* * * * *

Example 7: Pyramid Printing Using ForLoop

<script>
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
document.write(j+" ");
}
document.write("<br>");
}
</script>

Output:
1
1 2
1 2 3 
1 2 3 4
1 2 3 4 5


Example 8: Descending Numbers using For Loop

<!-- 10 9 8 7 6 5 ...1 -->
<script>
for(i=10; i>=1;i--)
{ document.write(i+" "); }

</script>


Example 9 : ODD Number Printing Using JavaScript

<script>
// 1 3 5 7 9 
for(i=1; i<=10;i=i+2)
document.write(i+" ");
}

</script>


Example 10 : Even Number Printing Using javaScript

<script>
//0 2 4 6 8 ... 
for(i=0; i<=10;i=i+2)
{
         document.write(i+" "); 
     }

</script>








No comments:

Post a Comment