Using Liberty Basic

Want to learn to program using Liberty Basic? Already programming in Liberty Basic but want to learn more? Follow this experienced programmer (Java) as he teaches himself this wonderful programming language.

 

Wednesday, May 24, 2006

Looping using the 'Do While' loop

In the last post we saw how we could use the 'while' loop to execute a section of code multiple times. Our example was that of needing to read in 10 numbers and printing out the sum of those numbers. In this post we'll see how we could have implemented the same functionality using the 'do while' loop. There was nothing intrinsically wrong with our earlier implementation using the 'while' loop, I'm just using the same functional requirements to illustrate the use of the 'do while' loop also.

Here is our example program demonstrating the use of Liberty Basic's 'do while' loop.


' =======================================
' Demonstration Of The 'Do While' Loop
' =======================================
' Description:
' This program demonstrates the use of
' the 'do while' loop to read in 10 numbers
' from the user. The sum of the 10
' numbers is calculated and output at
' the end of the program.
'
' Author: Eddie Meyer
' Date: 24th May 2006

' Variables
' ============

' The number of items to read in
NumItemsToRead = 10

' We are currently reading in item #CurrentNum
CurrentNum = 1

' The current total
Total = 0

' Loop until we have read in the required
' number of items.
do
if CurrentNum = 1 then
input "Please enter a number: "; InputNumber
else
input "Please enter another number: "; InputNumber
end if

' Update the current total
Total = Total + InputNumber

' Update the counter
CurrentNum = CurrentNum + 1
loop while CurrentNum <= NumItemsToRead

' Print out the total
print
print "The sum of the "; NumItemsToRead; " numbers you entered is ";
print Total; "."

end


The main points to note about the 'do while' loop are...

1) The 'do', 'loop' and 'while' keywords.

2) The fact that when you use the 'do while' loop as shown, you guarantee that your loop will always execute at least once. This is because the check of whether to execute another iteration of the loop is placed after the main body of the loop. Compare this with the regular 'while' loop that performs the check first and only executes the loop body afterwards. To my mind, this difference of whether the loop will always run at least once or not, is the main distinction between the two loops -- If you need your loop to always execute at least once, use the 'do while' loop, otherwise, use the regular 'while' loop.

I hope that makes some sense.

Eddie

0 Comments:

Post a Comment

<< Home