## Understanding For, Do, and while Loops

Level:

In our tutorial about if statements in Visual Basic 6 (Understanding if statements and conditions in VB6) we describe how conditional statements work - these can be used in loops as while so if you have not read that tutorial please do so now. Now continueing on with our original problem we described in our if statement tutoria how do we generate the Fibonacci series. Its formula is relatively simple:
1. Let x = 1, let y = 0.
2. Print x.
3. Let x = y + x
4. Let y = x - y
5. Repeat from 2.

This pseudo code will print out: 1, 1, 2, 3, 5, 8, 13, 21, ... as expected. But now how do we tell a Visual Basic program how to do this? The answer lies in using loops.

Loops provide the ability to repeatedly execute the same block of code, and to each time change values such that each run through the loop produces different results. Visual Basic provides four main kinds of loops: the classic Do-Loop, the Do-Until Loop, the Do-While Loop, and the For-Next Loop.

Do-Loops

The most basic form of loop in Visual Basic is the Do-Loop. Its construct is very simple:

Do
(Code to execute)
Loop

This, quite simply, executes the block of code, and when it reaches Loop, returns to the beginning of the Do Loop and executes the same block of code again. The same block of code will be repeatedly executed until it is told to stop executing. So let's try to apply this to our problem of generating the Fibonacci series:

Dim X As Integer
Dim Y As Integer

Do
Debug.Print X

X = Y + X
Y = X - Y
Loop

And, believe it or not, this code works! Well, sorta. If you try to run this code, it will indeed generate the Fibonacci series; however, it will continually generate and print out the next number infinitely--or, in this case, until it reaches an overflow error. This is known as the problem of the infinite do-loop, one that all programmers will experience, and some quite frequently.

Exit Do

So we clearly need some way to escape from the Do-Loop. You could, of course, simply End the program once you have calculated enough values, but what if you still need to perform tasks after you're done calculating? The answer is to use the Exit Do statement. Whenever your program reaches an Exit Do statement within a loop, it will exit the current loop.

So, let's try a somewhat different approach to the Fibonacci problem. We decide that we want to calculate only eight values of the Fibonacci series, so we'll keep a counter and increment it each time throughout the loop. Then, once the counter reaches eight, we'll exit the loop.

Public Sub Main()
Dim X As Integer
Dim Y As Integer
Dim cnt As Integer 'Our counter.
cnt = 1
Do
Debug.Print X
X = Y + X
Y = X - Y

If cnt >= 8 Then
Exit Do
Else
cnt = cnt + 1
End If
Loop
End Sub

And now we're talking! This program successfully computes and prints out the first eight values of the Fibonacci series.

Do Until

As an alternative approach to nesting an If-Statement inside the loop, and invoking Exit Do once we're done looping, Visual Basic provides a Do Until statement. Its syntax is the following:

Do Until (Expression)
(Code to execute)
Loop

(Expression) can be any legal logical expression that we wish to evaluate to determine whether or not to exit the loop. Each time the program reaches Loop it will evaluate this expression. If the expression is True, it will exit the loop for us, but otherwise it will continue looping.. So let's try rewriting our Fibonacci program to use a Do-Until loop instead of Exit Do.

Public Sub Main()
Dim X As Integer
Dim Y As Integer
Dim cnt As Integer 'Our counter.

cnt = 1

Do Until cnt >= 8
Debug.Print X

X = Y + X
Y = X - Y
cnt = cnt + 1
Loop
End Sub

Here we've replaced the hideous If cnt >= 8 Then ... Else: Exit Do with a very simple Until cnt >= 8. We must, however, still be sure to increment our counter every time through the loop, or else the Until expression will never be True, resulting in an infinite Do Loop.

Do While

In the place of Do Until, you can also use Do While. Its syntax is the following:

Do While (Expression)
(Code to execute)
Loop

(Expression) can be any legal logical expression that we wish to evaluate to determine whether or not to exit the loop. Each time the program reaches Loop it will verify that this expression is True, and if it is False, it will exit the loop for us. Thus, instead of exiting when an expression is True, it now exits only once this expression is false. Let's try rewriting our Fibonacci program to use a Do-While loop instead of a Do-Until loop.

Public Sub Main()
Dim X As Integer
Dim Y As Integer
Dim cnt As Integer 'Our counter.

cnt = 1
Do While cnt < 8
Debug.Print X
X = Y + X
Y = X - Y

cnt = cnt + 1
Loop
End Sub

For-Next Loops

In situations where you merely want to run the loop a predefined number of times, it can become quite tiresome to have to create and manage a counter for each loop, which is why we also have something called a For-Next Loop. This kind of loop allows you to specify a counter, to tell it to count from one number to another each time through the loop, and to exit once the counter has reached its upper limit. The syntax is as follow:

Dim I As Integer

For I = (Integer) To (Integer)
(Code to execute)
Next I

We used the variable name "I" above, as it is the most common name used for For-Loops; however, you can use any variable name you want, so long as the variable is of the type Integer. Now, let's improve our Fibonacci program even further:

Public Sub Main()
Dim X As Integer
Dim Y As Integer
Dim cnt As Integer 'Our counter.

For cnt = 1 To 8
Debug.Print X
X = Y + X
Y = X - Y
Loop
End Sub

In the example above, we first dimensioned cnt as an Integer, and then, in the declaration of the For-Next loop, set its value to 1. Each time through the loop, the value of cnt was incremented by 1 until it reached 8, at which point the loop was executed.

Exit For

As with Do Loops, there is a statement that can be used to exit a For-Next loop, and it is called Exit For. Simply invoke this statement anywhere within a For-Next loop and the current loop will be exited.

Step

By default, the variable used in the declaration of the For-Next loop is incremented by 1 each time through the loop; however, if you want to increment this value by a different amount each time through the loop, you can simply append Step (Integer) to the end of the For-Next loop declaration. If, for instance, we wanted to print out every even number counting backward from 20 to 0, we could do this using the following code:

Dim I As Integer

For I = 20 To 0 Step -2
Debug.Print I
Next I

So there you have it now you can use loops all over your Visaul Basic 6 programs. These are one of the most useful tools you have. You might want to bookmark this tutorial so that later you can reference back to this great VB6 loop examples. If you have any questions or comments please post them below.

###### This tutorail is released under the GNU Free Documentation License 1.2. The original can be found here.

If you enjoyed this post, subscribe for updates (it's free)

### can u help me under stand a

can u help me under stand a code whose output is:
1
12
123
1234(code finished)

Need to derive output without using NESTED Loops and IF Conditions.

### try this.. for x = 1 to 4 y

try this..

for x = 1 to 4
y = 1
for y = x to 50 - x
picture1.print " ";
next y
z = 1
for z = 1 to x
picture1.print x;
next z
picture1.print
next x

]
For i = 1 to 4
y = y & i
Next i
print y

### what is the code for reverse

what is the code for reverse of this like 1234,123,12,1?

### help.

please code a program that will accept 10 numbers and finds the average making use of the for and do statements. in[put box and message box commands must be used.

### HELPPP WITH VB

Ho how do i code a program to output the intials of a name only using one textbox. For example, i input Bill James into one textbox I want my label to output BJ. I can't get figure it out. Please, help would be greatly appreciated.
for

### Output the initials

Hi there! Take a look at this example:

Private Sub cmdOutputInitials_Click()
Rem Declarations of the inside procedure variables
Dim sFirstInitial As String, sSecondInitial As String, _
sTempInput As String
Dim lSpace As Long
Rem Inside procedure variables

'1.)
Rem Get the first letter of our txtInput textbox value _
and set it into sFirstInitial string variable
sFirstInitial = Left\$(txtInput.Text, 1)

'2.)
Rem Get the second space in the txtInput textbox _
and set it into lSpace long variable
lSpace = InStr(txtInput.Text, " ")

'3.)
Rem Get the txtInput value from the right and set it into _
sTempInput string variable
sTempInput = Right\$(txtInput.Text, Len(txtInput.Text) - lSpace)

'4.)
Rem Get the first letter of our sTempInput string variable value, _
and set it into sSecondInitial string variable
sSecondInitial = Left\$(sTempInput, 1)

'5.)
Rem Finally Get and concate the sFirstInitial and sSecondInitial _
string variables values and set it into _
lblOutput caption
lblOutput.Caption = sFirstInitial + sSecondInitial
End Sub

I hope this can help.
Regards.

tobz

### plz help...

write a program to input two one-dimensional array namely x and y with five values. find sum of their elements and store into third array namely z

### plz solve my problem...im thank full to u

write a program to input two dimensional array of order 3*3 and print sum of all the rows

### repeat loop

write a program using conditional operator to determine if a number is divisible by 5.Display the message"Divisible by 5" or "Not divisible by 5" accordingly......plzzz help someone

### input number to verifie as

input number to verifie as Number_Text
output number to verifie as Result_Text

Program in vb6

If Right(Int(Number_Text)) = "0" Or Right(Int(Number_Text)) = "5" Then
Result_Text = Number_Text & " is Divisible by 5"
Else
Result_Text = Number_Text & " is Not divisible by 5"
Endif

### help..........

help i dont noe any thing in looping and tomorrow is my x-am cud uhelp me under stand looooping???
pls.............
thanx
pls do now

### Tnx for this great VB 6.0

Tnx for this great VB 6.0 tutorial site!
I'm learning much from this site than our instructor.

### solve my program with do and loop

write a program that get the number that been like that at the first mod of this number should be to this number 0(n mod n=0)
and been between 2 to 500 at last show on one textbox

### loop codes(for)

can u help me under stand a code whose output is:
1
12
123
1234(code finished)
and this is displayed on the screen with a single time click on a command button

### this could be done easily

this could be done easily done with strings
strA = ""

for intX = 1 to 5
print strA
strA = strA & Cstr(intX)
next intX

OR

intA = 0
for intX = 1 to 4
intA = intA*10 + intX
print intA
next intX

### help me pls...

i'm working on programming where cashier can click on the system when customer have order the water...
i use checkbox, radiobox and button in my programming... and textbox to appear my result from checkbox, radiobox and button. but when i want to repeat second time, can't appear the output.... what script that should i use?? pls advice
(below is the coding )

Public Class FormFlavor
Dim ckName As String, RdName As String
Dim x As String, y As String, z As String
Dim result As Double
Dim juice As Double, Blender As Double, Flavor As Double

Private Sub FormFlavor_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

End Sub

Private Sub ckStraw_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ckStraw.CheckedChanged
If ckStraw.Visible = True Then
ckName = "You have selete Strawberry"
ElseIf ckStraw.Visible = False Then
ckName = ""
End If
TxtOrder.Text = ckName
End Sub

Private Sub ckVanila_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ckVanila.CheckedChanged
If ckVanila.Visible = True Then
ckName = "You have selete Vanila"
ElseIf ckVanila.Visible = False Then
ckName = ""
End If
TxtOrder.Text = ckName
End Sub

Private Sub ckYam_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ckYam.CheckedChanged
If ckYam.Visible = True Then
ckName = "You have selete Yam"
ElseIf ckYam.Visible = False Then
ckName = ""
End If
TxtOrder.Text = ckName
End Sub

Private Sub RdGreen_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RdGreen.CheckedChanged
If RdGreen.Visible = True Then
RdName = "green tea RM1.80"
ElseIf RdGreen.Visible = False Then
RdName = ""
End If
TxtOrder.Text = RdName
End Sub

Private Sub RdMilk_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RdMilk.CheckedChanged
If RdMilk.Visible = True Then
RdName = "milk tea RM1.80"
ElseIf RdMilk.Visible = False Then
RdName = ""
End If
TxtOrder.Text = RdName
End Sub

Private Sub RdRed_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RdRed.CheckedChanged
If RdRed.Visible = True Then
RdName = "red tea RM1.80"
ElseIf RdRed.Visible = False Then
RdName = ""
End If
TxtOrder.Text = RdName
End Sub

Private Sub RdShake_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RdShake.CheckedChanged
If RdShake.Visible = True Then
RdName = " Milk Shake RM 2.50"
ElseIf RdShake.Visible = False Then
RdName = ""
End If
TxtOrder.Text = RdName
End Sub

Private Sub RdSmoo_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RdSmoo.CheckedChanged
If RdSmoo.Visible = True Then
RdName = " Smoothies RM 2.50"
ElseIf RdSmoo.Visible = False Then
RdName = ""
End If
TxtOrder.Text = RdName
End Sub

Private Sub RdSoda_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RdSoda.CheckedChanged
If RdSoda.Visible = True Then
RdName = " Italian Soda RM 2.50"
ElseIf RdSoda.Visible = False Then
RdName = ""
End If
txtOrder.Text = RdName
End Sub

Private Sub RdYogurt_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RdYogurt.CheckedChanged
If RdYogurt.Visible = True Then
RdName = " Yogurt RM 2.50"
ElseIf RdYogurt.Visible = False Then
RdName = ""
End If
TxtOrder.Text = RdName
End Sub

Private Sub BtnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnDelete.Click
txtOrder.Clear()
End Sub

Private Sub txtOrder_TextChanged_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtOrder.TextChanged

If BtnJuice.Visible = True Then
txtOrder.Text = ckName & y
ElseIf BtnJuice.Visible = False Then
txtOrder.Text = ckName & RdName
End If

End Sub

Private Sub BtnJuice_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnJuice.Click

juice = 2.3

If BtnJuice.Visible = True Then
y = " Juice RM 2.30"
ElseIf BtnJuice.Visible = False Then
y = ""
End If
txtOrder.Text = y

End Sub
End Class

### help and support system

please send us email on how to do the help and support system in windows xp using the VB6.0
this is our project...

### help, asap!!!!

we have a project in object oriented programming.... We are about to create a program about help and support in windows xp using Visual Basic 6.0..hmn, please help us on how to do this.
thnx:)

### loop statement for our project's accountnumber

we need help...pls help us to make a code using loop statement...we need an account number in our project where the system will automatically compute for the account number of a new member..for example ACC-0001....we really need this please do help us...we will wait for your reply...

### gud evening

Assume FILE1 & FILE2 are sequential files containing numeric data.Based on the following program segment,what would be a good use for it?
Open "FILE1" for Input As # 1
Open "FILE2" for Input As # 2

C = 0
Do While Not EOF (1) And Not EOF (2)
Input # 1, num 1
Input # 2, num 2

If num1 <> num2 Then
C=C+1
End If
Loop
Close # 1,# 2

### help!!!

i have these projects that i can't finish
*find the sum of the series 1 + 1/2 + 1/3 + 1/4 ... 1/100
*reads an integer value and displays the sum of all the even integers starting from 2 and the input value, inclusive. Display an error message if the input value is less than 2.

### Salary Computing...

I'm working on a program that would compute the salary of the different workers in a company. It has radio buttons in it, and I want the figures to all get erased when someone selects a different option. I need some sort of a reset button, but I have absolutely no idea how. I know i would need some sort of loop....

### How can i solve this problem?

Write VB Program that will compute for the average rating of a teacher given by 10 students using Do while Loop

Thank you.
Good Tutorial!!

### Loops Within Loops?

I'm trying to fill a two-dimensional array with numbers. The last time I tried this was in QBASIC, and the simple way of doing that was to put one loop inside another -- the inner loop fills a row of data, completes, and then the outer loop runs the inner loop again, this time for the next row down. Here is what the code would look like in VB:

Option Explicit
Dim intN As Integer
Dim aintDiceRoll(1) As Integer
Dim aintTotal(1 To 6) As Integer
Dim aintResult(1 To 8, 1 To 6) As Integer

For aintDiceRoll(0) = 1 To 6
For aintDiceRoll(1) = 1 To intN
aintResult(aintDiceRoll(1), aintDiceRoll(0)) = Int(6 * Rnd + 1)
Next aintDiceRoll(1)
Next aintDiceRoll(0)

Yet for some reason this gives me errors... Is there a way to get around this, or should I just copy the inner loop code six times (since I know I want the outer loop to run six times)?

### computing

I am designing a program to calculate whether or not someone has passed or failed their language course depending on the mark out of 30 that they get. But i can't seem to add a loop in if they enter a number that is not betweem 0 and 30.

(here is the program so far):

'Declare variables
Dim Frenchmark As Integer
Dim Germanmark As Integer
Dim Spanishmark As Integer
Dim Totalmark As Integer
Dim Result As String
Dim Percentage As Integer

'Get the users French mark
Do
Frenchmark = InputBox("Please enter the pupils french mark")
If Frenchmark > 30 Then
MsgBox ("Please enter a whole number between 0 and 30")
ElseIf Frenchmark < 0 Then
MsgBox ("Please enter a whole number which is between 0 and 30")
End If
Loop Until Frenchmark >= 0 & Frenchmark < 31

'Get the users German mark
Do
Germanmark = InputBox("Please enter the pupils german mark")
If Germanmark > 30 Then
MsgBox ("Please enter a whole number between 0 and 30")
ElseIf Germanmark < 0 Then
MsgBox ("Please enter a whole number which is between 0 and 30")
End If
Exit Do
Loop Until Frenchmark >= 0 & Germanmark < 31

'Get the users Spanish mark
Do
Spanishmark = InputBox("Please enter the pupils spanish mark")
If Spanishmark > 30 Then
MsgBox ("Please enter a whole number between 0 and 30")
ElseIf Spanishmark < 0 Then
MsgBox ("Please enter a whole number which is between 0 and 30")
End If
Loop Until Spanishmark >= 0 & Spanishmark < 31

'Get the users total mark
Totalmark = Frenchmark + Germanmark Or Frenchmark + Spanishmark
Percentage = Totalmark / 90 * 100

'Decide if user has passed or failed course
If Frenchmark < 15 Then
Result = "Fail"
End If

If Frenchmark + Germanmark >= 30 Then
Result = "Pass"
Else
Result = "Fail"
End If

If Frenchmark + Spanishmark >= 30 Then
Result = "Pass"
Else
Result = "Fail"
End If

'Display the results on the form in text boxes
txtResult.Text = Result
txtPercentage.Text = Percentage

End Sub

### PLZ HELP ME ON HOW TO CREATE A SIMPLE WATER BILLING SYSTEM

HI!
I WOULD LIKE TO CREATE A SIMPLE BILLING SYSTEM THAT CAN CALCULATES THE FIGURES AND THEN PRINTS THE RESULTS AS WELL AS WHICH CAN STORE THE BILLS FOR LATER PREVIEWING,PLZ HELP,HELP GUIDE PLZ.It`s me Said,from TANZANIA EAST AFRICA.

### Do While

Hello!

I'm trying to figure out how to keep a running total of the sums of the numbers from 1 to the number entered within the input box. It is a Do While statement that has me stumped.

Thanks!

### Fibbonicci Series

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim term1, term2, term3, n As Integer
n = Val(InputBox("Enter no. of terms"))
term1 = 0
term2 = 1
For x = 1 To n
Debug.Print(term2)
term3 = term1 + term2
term1 = term2
term2 = term3

Next
End Sub

### Fibonacci Series

correct fibonacci series is
private sub form1_Activate()
dim x,y,n as integer
x=0
y=1
print x
print y
n=val(inputbox("enter no. of terms"))
for i=1 to n
x=x+y
y=y+x
print x
print y
next

thankyou so much

### perhaps there is a problem

perhaps there is a problem with the code on this page, just insert the satement
y=1
after y has been declared..
i guess it should work..

### Cant get to work

OkPublic Sub Main()
Ok I Cant get the public sub main to work what do I click command1 or what ?

### where to see the results

okay, the code runs, but where do i see the results? where are they printed. do i need to use MsgBox or what? and why do we need the Debug before print x

### how can this problem be solved

Federal Law requires hourly employees to be paid “ time-and-a-half” for work in excess of 40hours in a week. For example, if a person’s hourly wage is \$8 and worked 60 hours in a week, then his gross pay = (40*8)+(1.5*8*(60-40)) = \$560

Write a program that requires as input the number of hours a person work in a given week and his/her hourly wage, and then display his gross pay

### Module Module1 Sub

Module Module1

Sub Main()
Dim IntHours 'hours worked for the week
Dim IntOtHours 'just hours over 40
Dim IntPayRate 'hourly payrate
Dim IntRegPay 'pay for straight time
Dim IntOtPay = 0 'pay for OT
Dim GrossPay 'gross pay
Console.Write("Enter hours worked")
Console.Write("Enter pay rate")
If IntHours > 40 Then 'decides if OT pay is warranted
IntOtHours = IntHours - 40
IntOtPay = IntOtHours * (IntPayRate * 1.5)
IntRegPay = IntPayRate * 40
Else
IntRegPay = IntHours * IntPayRate
End If
GrossPay = IntOtPay + IntRegPay
Console.WriteLine("Regular Pay:" & IntRegPay)
Console.WriteLine()
Console.WriteLine("OT Pay:" & IntOtPay)
Console.WriteLine()
Console.WriteLine("Total:" & GrossPay)
Console.WriteLine("Press enter to exit")

End Sub

End Module

easy enough.

### how can i solve this problem

write a visual basic program that will accept as input the price of a product,the name of the product and the quantity purchase and display the amount due less the VAT .Assuming VAT rate is 17.5%.

I thought this small tutorial was pretty helpful.

### Fibonacci-Series

First I'd like to thank you guys for that awesome tutorial, keep up the good work, the tutorial is' far better than the crap we are told at our University!

But perhaps you could use another example since not everybody is familiar with the Fibonacci-Series and as a VB beginner you have to deal with two new tasks.

Thanks a lot

### Um... LOL?

Um, can you actually name one person you know who doesn't know the "Fibonacci-Series"?

### me! i don't know that

me! i don't know that "Fibonacci-Series"

### I don't

Erm, well I don't. Haha. I'll go look it up then. :p
Anyway nice tutorial on looping.

### Is it just me or is the

Is it just me or is the "For, Next" code wrong? In the initial example it properly shows going from the For command to the Next command and looping, but after the author says " now lets improve our fibonnacii sequence further" The "Next i" is missing from the code.

I think there are a couple problems with the code on this page, but this is my first day of programming. All I know is I couldn't get it to work unless I specified the value of x as 1 and y as 0. The For-Next loop also is wrong, according to my computer. It worked in this form:

Public Sub Main()
Dim X As Integer, Y As Integer
Dim count As Integer
X = 1
Y = 0

For count = 1 To 8
Debug.Print X
X = Y + X
Y = X - Y
Next count
End Sub

Otherwise, it yelled at me for Loop without Do.

### A suggestion

I think the for Next would also work this way

For count = 1 To 8
Debug.Print X
X = Y + X
Y = X - Y
Next ------------ you dont need to mention 'next count' . It would still execute.