| Liberty BASIC - Help Online |
Using Functions
Now that we've covered bringing data into your programs with input, displaying data with print, keeping data in string and numeric variables, and controlling program flow with if . . . then, we will bring one more way to light to flesh out your programs. Functions provide a means for manipulating program data in meaningful ways.
Look this short program:
input "Please type your name ?"; name$
print "Your name is "; len(name$); " characters long."
The second line demonstrates the use of the len( ) function. The len( ) function returns the number of characters in a string. The expression inside of the parenthesis must either be a string literal, a string variable, or an expression that evaluates to be a string. This identifies len( ) as a string function. There are other string functions (for example: val( ), trim$( ) ). The result returned is a number and can be used in any mathematical expression.
There are numeric functions as well. For example:
[start]
let count = count + 1
print "The sine of "; count; " is "; sin(count)
if count < 45 then goto [start]
This simple program lists the sines for the values from 1 to 45. The sin( ) function takes the value of count enclosed in parenthesis and returns the sine (a function in trigonometry, a branch of mathematics) for that value. Just like the len( ) function above, cos( ) and other numeric functions can be used as parts of bigger expressions. We will see how this works just a little further along.
Notice also the way the program counts from 1 to 45. On the first pass, count is equal to zero until it gets to the line let count = count + 1 which sets the data for variable count to be one more than its value at that point. Then the program prints the sine of count (the sine of one, in other words). After this, the line if count < 45 goto [start] checks to see if the data for count is less than 45. If it is, then BASIC goes back to the branch label [start] to do it again. This happens over and over until count reaches a value of 45, and then it doesn't go back to [start] again, but instead having no more lines of code to run, the program stops.
Going back to execute code over again is called looping. We saw this earlier when we first used the goto statement. In our first use of goto, the program always looped back. In this newest example program we see going back to execute code over again, but based on a condition (in this case whether count is less than 45). This is called conditional looping (you guessed it, the looping that always happens is called unconditional looping, or infinite looping).
Copyright (C) 2005 Shoptalk Systems
Liberty BASIC - http://www.libertybasic.com/