<% @ language="VBScript" %>
<% Option Explicit %>
Dim I,j
For I = 1 to 4
For j = 1 to i
Response.write i
Response.write "<br>"


Please explain me how this output is formed.

One bellow the other and is increasing

5 Years
Discussion Span
Last Post by gian88r

for loops execute the code between "for" and "next" until the condition next to the for statement is reached , so the first loop for example :

For I = 1 to 4 , will loop 4 times, the first time arround, I will equal 1 , the second time , I will equal 2 , third 3 , and the last time I will be equal to 4.

after that, I will be worth 5, since that is greate than 4, it will not execute the code a 5th time, and continue after the "next" statement

The fun thing in the snippet you posted, is that there is a nested loop that runs from value 1 to I (For j = 1 to i), every time the first loop goes through, it will see this loop and execute it from 1 to wherever I is at,

so the FIRST TIME ARROUND, it does from 1 to 1, so the inner loop execute ITS inner code once.
the LAST time (I = 4) the outter loop runs through, the inner loop will still execute from 1 to I which is then worth 4, so from 1 to 4.

//BIG LOOP starts (will run from I = 1 to 4)
//    ////
//    //small loop starts (will run from 1 to I)
//    //
//    // 
//    //    //inside small loop we print the value of "I"
//    //
//    //
//    //small loop ends
//    ////
//    //still inside BIG LOOP, but AFTER small loop is finished, we print <br> to switch line
//BIG LOOP ends

hope this visual kinda helps you figure out what goes on...


In ASP vbscript for loop is used to execute the code block iteratively when there is a need to run the same code block for number of times. Associated variable with vbscript for loop enables you to derive the different output from iterations of for loop. Vbscript for next loop executes the same code block repeatedly for specified number times.

Classic ASP VbScript Basics Examples:

You can see the live samples and examples of Classic ASP VbScript Basics from the following links:

VbScript For Loop
VbScript Reverse For Loop
VbScript While Loop in Classic ASP
VbScript Reverse While Loop
VbScript Do While Loop in ASP
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.