Wednesday, April 14, 2010

VB Scripting - FOR Looping Construct

Previous11121314151617181920Next


FOR Looping Constructs in VB Scripting


For Loop is used to run a piece of code iteratively for a finite number of times. The start and end conditions are known in advance and the counter automatically increments by one and this increment is by default.

FOR Looping Construct Example

Syntax

For [condition]
Code
Next

A simple for loop example

For i = 1 to 10
Msgbox "This loop is repeated "&i& " times"
Next

When you run this script the message box will display “This loop is repeated 1 times” and as you click the number increments till it reaches 10 times and also in the message the number is incremented and displayed.

For Step Next Looping Construct


In this kind of looping construct we actually change the increment to the desired number and the increment happens as we desire. To change the default increment value we use “STEP” along with the For Loop or you can have user defined increment like i=i+1 etc.

Syntax

For [condition] Step [increment/expression]
Code
Next


Example: We will use the above example and change the increment value as desired.

For i = 1 to 10 Step 2
Msgbox "This loop is repeated "&i& " times"
Next

Now when you run the script the value is incremented by 2 and the value in the message box will change and will display as “This loop is repeated 1 times” initially and then the value changes to 3,5,7,9 and the script terminates because next value is 11 and is greater than 10.

Assignment to do for FOR Looping Construct


1. Hope you remember the SELECT CASE statement in which we have looked at a code where in the user can perform a particular type of operation like addition, subtraction, multiplication and division. Now using the For loop try to ask the user how many times the operation should perform. For ex if the user enters 3 then the code should run for three times.

Look the script for this Select Case Statement

Click Here to view the Answer

2. Write a script to print prime numbers based on the user input for the prime number limit.

Click Here to view the Answer

3. Write a script to generate the Fibonacci series. Again ask the user for the limit.

Click Here to view the Answer

4. Write a script to print all the odd numbers till 100. Do not use the STEP statement.

5. Write a script to convert degrees to Fahrenheit.


Previous11121314151617181920Next

No comments:

Post a Comment