Wednesday, November 12, 2014

Do... While/Do...Until riddle.



In my tryst with QTP for last 8, I have came across many people aspiring to use Do…while/Do…Until in their code but are surrounded with lots of confusion or lack of know how. Pavan (my buddy) is not an exception. He hasn’t used Do…Until in his programming so far and seems to be gravely obsessed with it. This post is for him and for any one who want to crack the Do..While/Do..Until riddle.

Let’s get started.

For loop is used in QTP (or VB for that matter) is used when a block of code need be repeated for certain number of times – but what if the number of lines of code that need to be repeated is based on certain condition or conditions. The Do…While and Do…until comes to rescue. These statements enables you to repeat a set of code while a certain condition is True, or until a certain condition is True.

Example Time:

Suppose you want to add series of numbers but you wouldn’t like to do it infinitely. So, a restrictive condition should be required say, sum shold not exceed 100.
Dim sum = 1
Do While sum < 100
  sum = sum + 10
Loop

Generic Version

Do While (Conditional statement)
Some code…( is executed while conditional statement is TRUE)
Loop
In this code, the Do…While loop evaluates the variable ‘sum ‘every time to check whether it is less than 100. If it is, the next chunk of code is run. If not, it moves to the next line of code following loop. The loop keyword tells the code to go back to the Do.. While line and evaluate the new value of sum.
Note: Multiple conditions can be added in Do…While using AND operator.

Unlike, the Do…While statement repeats a loop while the condition is true, the Do…Until statement repeats a loop until a condition becomes true.

Example Time:
 
Dim sum = 1
Do Until sum >= 100
  sum = sum + 10
Loop
 
Generic Version

Do Until (Conditional statement)
   Some code…( is executed until the conditional statement becomes TRUE)
Loop
 
The block of code resembles the Do…While statement, except that this time the code is evaluating the sum variable to check whether it is greater than equal to 100.
Please also note that there can be a natural variation of these loop statements as following.
 
Do

   some code …

Loop While i>10
------------
Do

   some code …

Loop Until i=10
 
I think it is evident that set of code is executed at least once without evaluation of condition and next iteration is dependent on True/False of condition.

No comments:

Post a Comment