I made this widget at MyFlashFetish.com.

Ahad, 10 April 2011

What is DO WHILE and DO UNTIL?

Basic types of loops consist of DO WHILE and DO UNTIL

What can be said about DO WHILE loop is a continues executing the body of the loop as long as the comparison test is true but for the DO UNTIL loop is executes the loop as long as the comparison test is false. In other words, doing something until a condition is TRUE is the same as doing something while a condition is FALSE.
Do While X <= 10 is the same as Do Until X > 10.
This is how it will be when doing DO WHILE and DO UNTIL process:




AND


As for this is how DO WHILE LOOP  is used to print out all values of the Fibonacci Sequence until the values exceed 1,000 :  Subroutine to list the Fibonacci series for all values below 1,000


Dim i As Integer      ' counter for the position in the series
Dim iFib As Integer       ' stores the current value in the series
Dim iFib_Next As Integer ' stores the next value in the series
Dim iStep As Integer ' stores the next step size

' Initialise the variables i and iFib_Next
i = 1
iFib_Next = 0

' Do While loop to be executed as long as the value
' of the current Fibonacci number exceeds 1000

Do While iFib_Next < 1000

    If i = 1 Then
        ' Special case for the first entry of the series
        iStep = 1
        iFib = 0
    Else
        ' Store the next step size, before overwriting the
        ' current entry of the series
        iStep = iFib
        iFib = iFib_Next
    End If

    ' Print the current Fibonacci value to column A of the
    ' current Worksheet
    Cells(i, 1).Value = iFib

    ' Calculate the next value in the series and increment
    ' the position marker by 1
    iFib_Next = iFib + iStep
    i = i + 1
Loop

End Sub
 ----------------------------------------------------------------- 

The DO UNTIL LOOP is very similar to the DO WHILE LOOP. DO UNTIL LOOP is used to extract the values from all cells in Column A of a worksheet until it encounters an empty cell

Do Until IsEmpty(Cells(iRow, 1))
    ' Store the current cell value in the dCellValues array
    dCellValues(iRow) = Cells(iRow, 1).Value
    iRow = iRow + 1

Loop

In the above example, since the condition is empty (Cells iRow, 1) is at the start of the DO UNTIL LOOP.  The loop will only be entered if the first cell encountered is non-blank.

However, as illustrated in the DO WHILE LOOP you on certain time want to enter the loop at least once regardless of the initial condition.
At this time the condition can be placed at the end of the loop as follows: 

Do
  .
  .
  .
Loop Until IsEmpty(Cells(iRow, 1))


 Now you can see that the different is not soo big between DO WHILE LOOP and DO UNTIL LOOP but both have their own function of using.

Tiada ulasan: