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

Output:
1
22
333
4444

Please explain me how this output is formed.

One bellow the other and is increasing

Recommended Answers

All 4 Replies

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...

I hope this was not for an assignement cause its gonna be a little late! :P

You're welcome.

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
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.