Friday, May 20, 2011

Beginning Programming with Just BASIC -- Tutorial 4: Loops



Tutorial 4: For Loops and While Loops

Maybe you want to run a piece of code through several times. Instead of using GOTO, here's a snazzy way to accomplish this. There are two types of loops, the FOR loop and the WHILE loop. They are similar but are treated differently.

The FOR loop will run through the code a predetermined number of times, keeping track of how many times it has run through the loop. Here is how you would set up a FOR loop:

for i = 1 to n
    some code
next

For example,

for i = 1 to 1000
    print i
next

This code prints out the numbers 1 through 1000.

You can also have the loop count by an interval other than 1 (the default):

for i = 2 to 1000, step 2
    print i
next

This code prints out all the even numbers from 2 to 1000.

The WHILE loop is treated differently, but it can still function the same way. A WHILE loop will continue to run the code until a certain condition is met. For instance:

x = 1
while x < 1000
     x = 2*x
     print x
wend

As long as the value of x is less than 1000 x will continue to be doubled and print to the screen.

And that is all. There is no secret aspect of loops lurking in the shadows waiting to spring out and surprise you with complexity. What you see is all there is.

That said, let's write a program using loops:

Ever wonder how a computer calculates the square root of a number? Well, read further and you shall be enlightened.

You start with a guess, G, and you loop through this overwrite statement

G = (G + x/G)/2

until G is approximately equal to the square root of x.

Take note, however, that if you actually were going to take the square root of something in everyday programming, you'd use a built in function for that. Or just raise the number to the 1/2 power.

i = 0
print "Square root of what?"
input x
print "To + or - what precision? (%)"
input precision
precision = precision/100
lowerx = (1 - precision)*x
upperx = (1 + precision)*x
print "Guess?"
input G
while G^2 < lowerx and G^2 > upperx
    G = (G + x/G)/2
    i = i + 1
wend
print "The square root of x is "; G; " in "; i; " iterations."
end

This type of calculation is called numerical methods, and the subject is so vast that it has its own field of study.

goto [nextTutorial]

No comments:

Post a Comment