The HTML version of this manual has been created since it contains cross links to sections in this document for easier navigation.
This manual is not copyrighted and was written by Munawar Bijani for the benefit of himself to have a reference and for others who want to learn BASIC. This manual can be distributed at your desire.
Written By: Munawar Bijani; portion written by Graham Pearce.
Edited And Proofread By: The BPC Team
Modified For Correct Syntax By: Graham Pearce (A member of the BPC Team)
Chapter 31: string handling
Welcome to BASIC programming, a programming language which is very easy to learn and use! BASIC programming takes functions and statements and allows users to program using the basic concept of the english language. Although this manual doesn't cover each and every element in BASIC programming, you should be able to get the rest yourself as you make your programs by the knowledge you acquire through this manual. From time to time, I will provide links (specific to the HTML version) which will direct you to other sources such as BASIC libraries. Readers will be given practice exercises and homework assignments to varify that we are all up-to-date on what's being covered.
Freedom Scientific, Inc., has introduced BASIC programming for the Freedom Scientific Notetakers. This manual teaches you how to create programs in BASIC for your notetaker. It is not designed to teach you QBASIC for MS-DOS. Although we do discuss conversion, this manual is not official on it, and you may want to refer to another source for qbasic programming.
(Note that "e-cord" is also "enter." Therefore, if you were told to press e-cord, on a PC or Type N Speak or Type Lite, you would press enter. If you are writing this program on a PC, you may write your source in a text editor such as Notepad.)
In this chapter, you will be introduced to your first programming language. You may have to review it a couple of times to get the concept, especially if you have never programmed before. One thing I can advise you not to do is give up. It took me about a year to become a professional in BASIC programming. It will come to you, but it's not easy to spot... Keep your eyes open!
Before you move on, you need to know what you must have in order to write a BASIC program.
You must have the following utilities in your note taker to write a BASIC program:
For DOS: GWBasic (refer to appendix 3)
Run.bns is the program that runs the BASIC program that was compiled. Compile.bns takes your source file and turns it into a language which run.bns understands and therefore runs it. These two utilities must be in your unit before attempting to run or compile the programs you create or download.
The run.bns utility can be downloaded from the following location:
The compile.bns utility can be downloaded from the following location:
Once you have the appropriate utilities in your notetaker, you have what you need to create those files with a *.bas file extension! MAY THE NOTETAKER BE WITH YOU!
When you hear the word "source," and you're listening to a discussion on programming, what source means is the file(s) which was compiled by compile.bns or the compiler to create the program file. For instance, when we start writing programs, the file in which we write our code is the source file. The code is the source code.
To start off, lets create a file in our unit called myprog.src. Why do we give it a .src extension? This extension is common in BASIC source code files, and is assumed by compile.bns if no extension is supplied. In myprog.src, it is recommended that you play around with code often, so you get a good hand on it. I won't say "OK, open your myprog.src file, and write the following code in it," because if I do that, I will be giving you answers, and telling you what to write. It's like you're in high school now, in Algebra... Take notes if you want, otherwise don't. It won't hurt me. It's up to you! Yes, I will be supplying sample programs throughout this manual, which you may copy over to your source file and compile it, but again I won't force you to! Ok Ok... Enough with that, lets start our journey into BASIC programming!
When you look at a BASIC program's source code, you will find that every line has a number assigned to it. In BASIC programming, you are required to number each and every line you write. Because of this, if you want to insert some code between lines two and three, it's not possible. That's why a good programmer always sets their lines in intervals such as 10, 20, 30, Etc., instead of 1, 2, 3. When you number your lines in intervals, it is easy to add/revise components in your program. I will not be setting my sample programs in intervals here, however it's highly recommended that you do, especially when you start writing your own programs and revising them. The program below is the first sample program I will be discussing with you.
1 print "hi"
This is a source code. Obviously, the line numbers in this program are 1 and 2. Let me tell you in brief about these pieces of code.
In line 1: 1 print "hi", instructs the program to display the word "hi" without the quotation marks. If you are wanting to display a message to the screen and have it read by the synthesizer (if it's active,) you would use the print command. Simply create a line with: print "Text to be displayed goes here." Put the message you want to be displayed/spoken in quotation marks as shown here. When you are somewhat familiar with BASIC programming, refer to appendix 8 for a detailed explanation on this command.
Now look at line 2 of the above program: 2 end; instructs the program to terminate. This is the end statement, or command. For detailed information, see section 13.
Notice, in the above program, that a structure for a "line" in BASIC programming is a number, followed by the line's contents. All lines must be in order. For instance, if I write the program:
5 print "Another program?"
This program is invalid, because of course, 2 comes before 5, not after, dugh! This program will not compile. OK, so I catch this error and revise my program:
2 print "Another program?"
This program will compile correctly, since the line numbers are not mixed up. In the next chapter, we'll discuss what we call the goto statement. Before we get into discussing statements and such, you must understand the way BASIC programs are run.
BASIC programs, for the most part, will execute from top to bottom. For this reason, the following program will display: "What's up?" "Doing OK?" and not vice versa:
1 print "What's up?"
2 print "Doing OK?"
We can, however, change the order. For instance, we can have a program execute to line 5, jump back to 2, then 4. Also, we can have a program execute certain lines based on what happens at runtime (when the program is executed.) The goto statement, discussed in the next chapter, is one example to this fact.
The goto statement jumps the program to the specified line number. The program will execute from that line down, unless instructed otherwise. For example, if you write the following program:
1 print "OK now instead of executing line 10, we're going to tell"
2 print "our program to go to line 11 and execute there..."
3 goto 11
10 print "No! You skipped me!"
11 print "Hehehe looks like line 10 got skipped? LOL!"
When the program is executed, it will execute lines 1, 2, and 3. On line 3, however, we wrote a goto statement, which instructed the program to execute line 11 instead of 10 like it should. This means that line 10 will be ignored, and line 11 will be executed. Also, since line 11 doesn't contain any statements to tell the program to jump back somewhere, and there are no lines after 11, the program will end. Any time a program reaches the last line, and it's not instructed to go back, it will end. Therefore, to end the program at line 11, it is not necessary to have an "end" statement. The next chapter will discuss some advanced programming. It should be fairly easy to grasp, though.
Another way to tell the program what to do is to write an if...then...else... structure. This structure compares something, and if the comparison is true, it will do this, otherwise it will do this. Look at the program below.
Note: to find an explanation of variables, see section 9.1. We will refer to variables briefly here.
1 print "press y to continue, n to exit."
2 get exit$
3 if exit$ = "y" then goto 8
4 if exit$ = "n" then goto 10
5 else goto 1
7 print "you pressed y."
10 print "you pressed n."
The source you looked at above has something called an if...then...else... statement. This means that if this is true, then do this, otherwise do this. The source code above says that if exit$ yields "y", then goto 7, if it yields "n" then goto 10. If it yields anything else besides "y" or "n", goto 1.
If...then...else statements can have other comparisons rather than equal to. For example, you can have a statement say that if y is greater than 7, goto 8. This is done by: if y > 7 then goto 8. If the if statement is true, its command will be executed. Otherwise, it will look for an else statement. If it doesn't find one, it will begin execution just after the if statement.
As it was mentioned earlier, the get exit$ statement will be discussed later. This chapter is dedicated to this topic.
The get exit$ statement simply tells the program to get a keystroke and put it in the specified variable. (See chapter 9.1 for explanation on variables.)
1 print "press y to continue, n to exit."
2 get exit$
Assuming you read section 9.1, the program here will display the message: "Press y to continue, n to exit." On line 2, you see the statement: get exit $. The get statement gets a keystroke from the user, and puts it in the specified variable, in this case exit$. Since exit$ now holds what the user pressed, you could write an if...then...else... structure to execute statements and/or goto lines based on what the user typed.
The get statement will except multiple arguments. For instance: print "Enter your grades.":get g1$, g2$, g3$, g4$, g5$, g6$
These set of statements will print "Enter your grades." Assuming the student has six classes, six variables are provided for input. Therefore, if the student got all A's, they would execute the following commands: press a, a, a, a, a, a. This is because the get statement is told to get six keystrokes. Note: when passing multiple arguments, it is very important to notify the user that you are doing so, and therefore the user knows how many elements of data need to be entered.
It is important to note that the get statement does not except numerical variable types. You cannot press a number 2 when prompted with the get statement. If you are wanting to ask for a number, you must use the input statement discussed in the next chapter.
The get statement also recognizes corded characters (characters which are press in conjunction with the spacebar (specific to the BNS, BLT, and BLM FSNotetakers.)) When a character is corded, the variable which the keystroke is passed to holds a percent sign (%) followed by the corded character in uppercase. Thus, if the user entered b-cord as their prompt, the appropriate variable would hold: "%B". Note: the u-cord keystroke is intercepted by the system and will not be passed to the program. Therefore, it is advised that the author refrain from requiring the user to press u-cord.
For this section, please read 9.1.1 for variable concepts.
The input statement provides the user with an edit field to type a piece of data (answer a prompt,) then press e-cord to resume execution. The input statement is set up like the get statement. For instance, the line: 2 input n$ tells the program to provide the user with an edit field, and what the user types, store in the variable n$. Once that process has finished, you can have an if...then...else... structure to do stuff based on what the user types, having your comparison be the variable, and what you want to be on the other side.
1 print "Enter your name:"
2 input name$
3 if name$ = "Munawar" then print "Yeah, you're the right person."
4 else print "Why did you access this program?"
Notice that the text I want compared is in quotation marks. For a more complete discussion on variables, see section 14.1.
The input statement also excepts multiple arguments similar to the get statement.
1 print "Enter your address line1, line2, then your age:"
2 input address1$, address2$, age
It is important to notify the user of the exact order in which data should be entered. Numerical data can only go into numerical variables, and strings can only go into string variables.
Unlike the get statement, the input statement will except numerical variables as their input. One more syntax for an input statement is as follows:
1 input "Enter your age", age
Instead of having the prompt spoken by a different print statement, you can tie it in with the input statement, making the prompt and input box a single statement rather than two separate ones.
Look at this program source, and see if you can tell what it does:
1 print "hi my name is Munawar."
2 print "press y to continue, n to exit."
3 get exit$
4 if exit$ = "y" then goto 8
5 if exit$ = "n" then goto 20
6 else goto 1
8 print "type in your answer to this question."
9 input "What's 1+1?", answer
11 if answer = 2 then goto 14
12 else goto 17
14 print "right."
17 print "wrong"
20 print "you have chosen to exit."
Do you get it? If not, go back and review the chapters, then come back and try to figure it out!
Ok now that we have been through this much, it's time for your first homework assignment!
I want you to create a program that first displays, hi my name is xxx. Replace xxx with your actual name.
Second I want you to prompt the user, press b to begin, n to exit test program.
After that I want you to program it so that if the user presses b, it will ask you to answer a question. Make that question anything you want, and then fill in lines for the appropriate responses.
In this chapter, we'll discuss managing files through your program. You have endless functionality with files through your BASIC programs. In your program, you can:
You might sweat when you hear the word "variables." They're not as complicated as you think. This is not true, however, when your whole program is based on variables, but we'll discuss that in later chapters.
First let's start off with what is a variable?
A Variable is simply a letter, word, or string that stands for something else. Remember Algebra class? The letter x can stand for 1, 2, 3, or even 2,000. This is how a variable works in BASIC programming.
See below for example:
When I type the source:
1 Get exit$
2 If exit$ = "y" then goto 5
3 else goto 1
5 print "you win!"
Notice the get exit$ statement. The get exit$ statement contains a variable. The variable is the exit$.
The exit$ can stand for anything, any key-press. This is why we use if exit$ = "x" then goto xxx
The get simply tells the program to get a keystroke, and put it in the specified variable, in this case exit$.
So you can type the following, and it will still mean the same.
Notice that we did not change the word get. Also note that the variable comes followed by a dollar sign. You can also use variables in the input statement.
Do you remember the input n$ statement? Here, the n$ is a variable. The variable used in an input statement will almost always hold a string of text, rather than one character such as that of a get statement. Next we will start using variables in a very handy feature.
We can have a BASIC program create a file and write text in it.
We have already learned how to write text to the screen, but what if we wanted some text to be written to a file for later viewing?
It's very simple.
Please note that variables will come in handy here.
To create a file, we need four things:
1. The line number of course.
2. The create statement.
3. The file number.
4. The file name.
To start creating a file, assume you are on line 400.
Type the following:
400 create 1,"test.txt"
First we have the line number (400).
Then we have the create statement (create).
After that we have a number, which specifies the file number. These can go from 1 to 3. If you are creating more than one file, and you put both of them to have the same numbers, one file will be overwritten, so be careful!
After the file number (1) we have a comma then a quote.
Finally, the file name (the name of the file to create) and then another quote.
Note that all files created will be added to the end of your file list. The file number, 1-3, just tells the program what file you are referring to, it will be used when we start writing text into the file. It does not mean that the file you create with a file number of 1 will over write your clipboard file. Trust me, I thought this way myself, but the only way I found out was by trying.
Now what if we want the user of the program to specify the file name and not the program?
For example: You create a program that asks, "type in the file name you want this data to be stored in."
Of course the input statement does this, but how do we tell the program to take the data the user types, and put it into a file name? This is where variables come in handy!
Suppose you have a source like this:
1 input k$
2 create 1,k$
Can you guess what this does?
It's simple. The input k$ tells the program to wait for the user to type something and press e-cord, right? The text that the user types into the program then is substituted for k$, therefore if a user types in: Test.txt, The k$ variable is now test.txt
Thus, to have a user specify a file name himself and not have the program do it for him/her, you would put the following:
1 print "type in a file name and press e-cord"
2 input f$
3 create 1,f$
Since we specified f$ as our variable which holds the file name, we tell the program that the designated file name is in the f$ variable. This is why instead of putting a file name in quotes, we specify f$ as a replacement. Take note that the variable is not enclosed in quotation marks. This is because anything enclosed in quotation marks is read as literal text. For instance, if we wrote the following statement in relation to the small program shown above, the file created would have a name of "f$".
3 create 1,"f$"
We don't want this, now do we? We want the program to take whatever is in f$ and use it as the file name, not "f$" itself, dugh!
Now that you have created the file, how do you write something in it? To do this, you need the following:
The statement to write something into a file does not have to be right after the create statement, but here we are going to put it there, so no confusion is caused.
1 create 1,"test.txt"
2 fprint 1,"hi"
Line 1 just creates the file. Line 2 is the one that actually writes the statement into the file.
To write something into a file, we use the fprint statement. This statement is set up respective to the following syntax:
1 fprint [file#],"[text to write]"
The file# is the number which you assigned the created file. For instance, if the following statement was written, this number would be 3: 1 create 3,"test.dat"
After we specify the destination file, we need to tell the program what to write into the file. This text is surrounded by quotes, obviously, unless you specify a variable or a numerical value.
1 input "Type your designated file name here", j$
2 create 1,j$
3 input "Type text", q$
4 fprint 1,q$
If you are wanting to input multiple data elements into a file at one given time, writing the fprint statement 10 times would be very time consuming. A shortcut does exist for this procedure. Say you have two variables to input to a file. You could do it like this, assuming the variables are a$ and b$:
1 fprint 1,a$:fprint 1,b$
This, fortunately, is not necessary. You could accomplish the same effect using the following syntax:
1 fprint 1,a$, 1,b$
Notice that before data is written, the file number must be specified.
In this section, we're going to do the exact opposite of what we did in section 9.4. It is possible to read data from a file and store lines in variables. To accomplish this, we use the finput statement. It's pretty logical-- fprint prints data to a file, and finput inputs data from a file into the program.
The syntax for this statement is as follows: 1 finput [file#],[variable to store the data in]
Again, we must tell the program what file we are referring to (this time by file number, not file name.) Once that is done, our second argument is the variable in which to store the line that was grabbed from the file.
Say, for instance, we had a file which we created with a file number of 2. We then wrote 3 pieces of data into it as follows:
This is a cool file.
We then wrote three finput statements as follows:
3 finput 2,msg$
4 finput 2,age
5 finput 2,msg2$
The msg$ variable now holds the text "What's up?" The age variable now holds the number 15; the msg2$ variable now holds the text "This is a cool file."
Notice that the pointer always reads the next line down. In order to move it back up to the top, either close and reopen the file (this will be discussed in later sections,) or read from another file. Also, take note that the lines being read must be in variable types respective to the line grabbed. For instance, if the line grabbed was "hi", and you stored it in the variable age, you would receive a type mismatch error.
If you have read section 9.4.1 already, you will find both sections identical. The finput statement can grab multiple lines in one statement. For example, you could write:
1 finput 1,h:finput 1,a$
This is fine for short scanning, but what if you had several variables to scan and grab; saving and loading a game may be a perfect example. You could do this:
1 finput 1,h, 1,a$
As long as you don't exceed the chars per line limit, you're fine doing this. It takes up less space and less typing is done as well.
You may be wondering, "What if I have a file in my system which I created through some other source-- How do I make the program aware of this file?" This is what we're going to discuss here.
To open a file through your program, use the open statement. It's set up very similar to the create statement. The syntax is as follows: 1 open [the number which you want to assign to this file(1-3)],"[the file name which you want to open]"
You must assign this file a number (so the program can reference it.) The next argument is the file name you wish to open. This must be an existing file or the program will return a "file doesn't exist" error message. Say we opened a file called "MyFile.txt." We assigned it a file number of 1. This would be accomplished by something similar to: 1 open 1,"MyFile.txt"
Now we may treat it like any other file (since it has a number.)
If you do open files, it is important to close them after modifying them as required. To do this, use the close statement. The syntax is: 1 close [1, 2, or 3]
Going back to our MyFile.txt example, if we want to close it, we would write close 1. Refer to the file by its number, not name.
The following program is a summary of what we have learned so far. Note that this program is large. When you do start creating official programs, the lines might reach to 1000! For example my unending adventure goes up to about line 300.
1 print "hi. this is a test program."
2 print "press y to continue n to exit."
3 get con$
4 if con$ = "y" then goto 8
5 if con$ = "n" then goto 27
6 else goto 1
8 print "my birth date is 08/04/87."
9 print "this date will now be written to a file."
10 print "type the file name you want this"
11 print "date to be stored in. please include a .txt extension."
12 input file$
13 create 1,file$
14 fprint 1,"08/04/87."
15 close 1
17 print "another file will be created for you to type comments on this program."
18 print "file name:"
19 input "A .con extension is added automatically", filec$
20 create 2,filec$".con"
21 print "type comments, 126 characters max:"
22 input comt$
23 fprint 2,comt$
24 close 2
27 print "you have chosen to end the program."
If you do not get what this program is supposed to do, review the chapter, then come back and figure it out! If you do get what it does, move on to homework assignment number 2!
Here is your next homework assignment.
I want you to create a file called hwk2.src. In that file I want you to write a program source.
First introduce yourself. Then I want you to ask the user to create a file with the name they desire.
Once they have specified the file name, have the program create a file with that name they specified.
Then in the file the program created, I want you to have the program write the following string into the file:
"I have done it!"
Well that's as simple as I can make it. LOL!!!!!
I know we should have talked about this earlier, but it's better late than never, right?
Refer to this source:
1 input "What is 2+2?", c
2 if c = 4 then print "Right":end
3 else print "No! Try again! It had to be a type-o!":goto 1
Notice the input statement. What does this program do??
It asks, what is 2+2?
Then it waits for you to type the answer and press e-cord. The answer is 4.
If the user types 4 and presses e-cord, the program will print "right," as we learned in the earlier chapters. However, if the user types anything else besides 4, the program will print the message about the wrong answer. This action is determined by the else statement found in line 3.
The else statement, in general, makes a decision if the if comparison, for whatever reason, returns false.
Notice that in the previous example programs, we had a line that simply had the word end. What does this actually mean?
This statement is pretty logical. It simply tells the program to end.
1 get stroke$
2 if stroke$ = "y" then goto 5
3 else goto 8
5 print "you pressed y"
8 print "invalid key press"
The source first gets a keystroke, and puts it in a variable called stroke$. After that we have the if statements and else statements.
Then we have the corresponding lines. Notice that we have an end statement in lines 6 and 9.
Once the program reaches these lines the program will end. Thus, when the program reaches line 6, therefore if the user presses y, the program will not go on to line 8 because it is instructed to end at line 6. This is useful when you have lines for different actions right next to each other.
(NOTE THAT THE FOLLOWING SECTIONS GET INTO SOME ADVANCED PROGRAMMING AND SHOULD NOT BE ATTEMPTED IF A CLEAR UNDERSTANDING OF THE PRIOR CHAPTERS IS NOT VARIFIED.)
The let statement is used to assign values to variables manually. For instance, you can use the let statement to assign a value of 6 to the variable X. Furthermore, you can insert expressions into this statement. You can, for example, have y yield x+2. Before we start using the let statement, we will look at the two types of variables that are in BASIC programming.
If you recall, in section 9.1, we discussed variables. The variable we were referring to was the variable followed by a dollar sign ($.) In the next two sections, we will discuss this type of variable, as well as the variable not followed by a dollar sign.
The variable which is followed by a dollar sign, holds a letter, word, or string of characters. Therefore, the variable name$ can contain a value such as "hi." It cannot contain a numeric value such as 6. Thus, if the variable name$ contained something like "this is my name," anytime you specify this variable, the sentence "this is my name" will be passed.
This variable can contain a string of letters and numbers, but it cannot contain numbers by themselves. You cannot create expressions with this variable, it will create a type mismatch error.
This variable type contains a numeric value such as 6, 7, or 8. You cannot put letters into this variable. The variable y cannot contain a value such as "hi," but it can contain a value such as 500. You can have this variable return a value of an expression. For instance, you can have it contain a value of 5+5-2+15. When this variable is called, it will return a value of 23, since that is what 5+5-2+15 yields. Using this variable, you can create expressions such as x-y. Let x have the value of 5, and y have the value of 2. This expression will take 5-2 and return 3. Next we will look at how to assign values to variables.
We can use the "let" statement to assign values to variables. We need two important things.
First, you have to specify the variable to which a value will be assigned. Then you need the value to assign to the variable. Thus, you would use the following format to assign a value of 2000 to the variable x
let x = 2000
It's pretty logical, isn't it? Now how do you assign a string to a nonnumeric variable?
The value here must be enclosed in quotation marks. Thus, to assign a string hi my name is Munawar to the variable test$, you would use the following format:
let test$ = "hi my name is Munawar"
To create a numeric expression with a variable, and have the program assign that value to the variable, you would use something similar to the statements below:
1 'this statement will assign a value of 10 to the variable p
2 let p = 10
3 'the next statement subtracts 2 from p,
4 'and puts it in the p variable
5 let p = p-2
6 'this statement takes the current p value, subtracts 2 from it,
7 'and substitutes the result in the variable p,
8 'therefore making p now have a value of 8
Notice that some statements were behind an apostrophe character. This means that that line will not be compiled, instead it will act as a comment line. This is useful when showing your source to a person who is just learning how to program in BASIC.
Note that you do not have to include the word let in your let statements. You can simply type:
q = 5
and it will mean the same as:
let q = 5
This goes the same with nonnumeric variables. y$ = "hello" means the same as let y$ = "hello"
Sometimes you may create programs that involve fighting in tournaments, trivia, keyboard typing, Etc. All these types of programs require keeping track of some kind of amount such as energy for tournaments or point scores for trivia and keyboard typing programs. Now the question comes to mind, "how do you make a user aware of points or energy?"
Yes you can send warnings if the value is reaching zero, but how do you give the user their current status when it is at 2000?
First, in order for you to keep track of points or energy, the value must be in a variable, which, if necessary, must hold a numeric value. Then you can just use the let statement as mentioned earlier to add and subtract from the current value based on the actions taken. Now how do you give the user their current energy amount? For example you might have "congratulations, you win! your current health is," then you print their current health.
For this example, assume your energy is returned by the variable h. You would type something like:
1 let h = 50
2 'this statement assigns a value of 50 to the variable h
3 let h = h-30
4 'this statement subtracts 30 from h, thus making it 20
5 print h
6 'this statement prints the current value of h
7 'to the screen
As you can see from this example, it is pretty simple to give the user their current point score. Let's refer back to the example where we said "congratulations, you win! your current energy is"
Do you know how we would now print the current energy? Assume the energy is located in the variable x. To complete our task, we would use something similar to:
1 print "congratulations, you win! your current energy is"
2 print x
This is the long way to do it. The shortcut is:
1 print "congratulations, you win! your current energy is":print x
You can put more than one statement on a line. To do this, put a colon (:) between the statements to separate them. For example:
1 print "enter your name.":input name$
This is useful when you don't want to waste time!
This section does not need to be tended to; I just thought of including it in case you're looking at another author's source code.
Some authors, including myself, like to keep their variables organized. You can have variables named similarly to each other to show relationship as shown below:
Obviously, this is a fighting game. Charhealth holds the character's (your) health, and challhealth holds the challenger's health. Now, say that the player, being you, could also buy health. This health would be added onto the default value of your health. Say we named this variable (the variable which holds your purchased health) charhealthadd (for screen reader users, it's pronounced char health add.) Naming variables this way could leave the author and/or source-viewer confused. You could capitalize the first word of the variable I.E. CharHealthAdd. However, what if you prefer to write your program in all uppercase like some authors? When naming variables, you are permitted to use the period (.) in your variable name. Several authors use the period to show relationships between variables. For instance, in previous chapters, we discussed volume control, rate, Etc. Notice that all variables which held speech settings (current rate value, pitch value, volume value, and frequency value) began with the "speech." prefix. Following the period, the word respective to its value was written. For example, the variable which held your pitch setting was speech.pitch, or simply s.pitch. Likewise, the variable which held your volume value was speech.volume, or s.volume. Why do all these variables begin with the "speech." prefix? They're all related to speech levels and settings, dugh! You can do this for your variables; it's not just for built-in variables. Going back to our fighting program, a more sensible way of writing it out would be as follows:
3 health.char.add=50 'value can change
Notice that we used the period naming convention to write these variables. A viewer and the author will now be able to understand the relationship of these variables. They all deal with health, so we gave them the "health." prefix. Next, the character's health was stored in a variable which also contained health attributes, so we gave it a name of "health.char" for character. And on it went to health.char.add. Notice this variable has two periods. This is because of relationship terms. It deals with health "health".; it also deals with the character "health.char."; and it's the add on health "health.char.add".
One thing to keep in mind when naming variables like this is that the variable name is limited to 40 characters. If a dollar sign exists, it's counted as one character. This is why you can't have the following line in your program or a "line too long" error message will result:
Who would want a variable name this long anyway? It's important to keep in mind that you don't want your variables too long or a lot of type-o's will cause your program to malfunction. So, instead of health.char.add, you may want h.c.a.
Now that we know how to insert more than one statement on a line, and we know how to use variables, we need to be aware of some important notes, which we must follow for the program to be compiled correctly.
• 1. The maximum characters per line is 128. This means that you can type up to 128 characters on one line. If this number is exceeded, the program will not compile, and will return a "line xxx too long" error message.
• 2. Don't use character string variables to specify expressions. Example:
This will create a syntax error when compiling and running the program.
• 3. Always close a file before opening another one. Example:
Say you created a file called "test.txt" with file number 1, and another file called test2.txt with a file reference point of 2. You want to write something in file number 1, so you open it by the following:
400 open 1,"test.txt"
Then you want to write something in file number 2, but number one is still open. Close file 1, by performing the following:
400 close 1
Then you may open file 2, and make sure you close it as well.
• 4. If you are assigning a string to a string variable, you must enclose the string in quotations. Example:
400 let test$ = "hi"
• 5. When telling the program to use a variable to assign values, do not enclose the variable in quotation marks. Example:
Now that we have learned how to use variables in expressions, say you are keeping track of energy. If the energy reaches 0, you lose, right? To do this, you would do something similar to:
1 let p = 5
2 let p = p-5
3 if p = 0 then end
This sample program uses the p variable and if it yields 0, the program will end. But what if the energy is below 0, in the negatives? Do you have to write an if for every negative number? That will take the rest of your life! There's a shortcut to doing this. You can create an if that will say that if the point score is below 0, to end. Then the question comes, "what if the energy is exactly 0?" In this case, you would put the if statement to take action if the number is less than 1. Example:
1 'this statement will take action if the variable h is less than 0
2 let h = 20
3 let h = h-20
4 let h = h-1
5 'now h has a value of -1
6 if h < 0 end
7 'this statement tells the program that if the h variable is less than 0, to end
8 let h = h+1
9 'now h has a value of 0
10 if h < 1 end
11 'this statement tells the program that if
12 'the h value is less than 1 to end
Likewise, you can also use greater than signs to specify actions
1 let h = 6
2 if h > 1 end
This statement tells the program that if the h value is greater than 1 end.
The following program raps up the main lessons we have covered
1 print "test"
2 let sentence$ = "hi my name is Munawar"
3 let h = 20
4 print sentence$
5 print h:if h > 15 end
6 if h < 200 end
(WARNING! THIS CHAPTER, IF APPLIED TO A BRAILLE LITE MILLENNIUM, WILL CAUSE THE SYNTHESIZER TO ACT UP. THIS IS BECAUSE AN UPDATE WAS PERFORMED TO THE MILLENNIUM SYNTHESIZER IN ORDER TO INSERT DOUBLE TALK. THEREFORE, THE UPDATED SYNTHESIZER DOES NOT SUPPORT THESE FUNCTIONS DISCUSSED IN THIS CHAPTER.)
You can control the following synthesizer settings:
In this chapter, we will discuss how to change these settings as well as return their current values. This chapter is useful if you are trying to create a program, which involves conversations.
To change the pitch of the synthesizer, you must use the "setpitch" statement. Following this statement, there will be a number from 0 to 255. This number specifies the pitch level. Example:
1 setpitch 30
sets the pitch of the synthesizer to 30. You can get the current setting of the pitch as well.
The current pitch level of the synthesizer is returned by the s.pitch variable. Thus, if you set the synthesizer pitch to 100, the s.pitch variable will return a value of 100.
Note that modifying the s.pitch variable will not affect the synthesizer pitch.
To return the current setting of the pitch to the screen, you would use something similar to the following:
1 print s.pitch
Since s.pitch is a variable, it can be printed by the example above. Next we will look at changing the frequency of the synthesizer.
To change the frequency of the synthesizer, you must use the "setfreq" statement. Following this statement there will be a number from 0 to 16. This number is used to specify the frequency level. Thus, to set the frequency of the synthesizer to 10, you would use something similar to:
1 setfreq 10
Just like the setpitch value, you can return the current frequency setting. The current setting is returned by the s.freq variable. Thus, to print the current frequency value to the screen, you would use something similar to:
1 print s.freq
Therefore if you set the frequency setting to 15, and you return the setting by the s.freq variable, it will return a value of 15. Example:
1 print "hi"
2 'prints the word hi
3 setfreq 5
4 'sets frequency to 5
5 print "hello"
6 'the word hello is said in the frequency level 5
7 print s.freq
8 'prints the number 5 to the screen,
9 'since the frequency setting is 5
As you can see from this example, the s.freq variable is simply a numeric variable, which is built-in just like s.pitch. Next we will look at how to change the volume of the synthesizer.
To change the volume of the speech synthesizer, you must use the "setvol" statement. After this statement, there will be a number between 0 and 15. This number specifies the volume level. Thus, to set the volume of the synthesizer to 5, you would use something similar to:
2 setvol 5
You can return the current volume setting by the speech.volume variable. Thus, to print the current volume setting to the screen, you would use something similar to:
1 print speech.volume
In the next section, we'll discuss the rate setting of the synthesizer.
To change the rate of the synthesizer, you must use the "setrate" statement. After this statement there will be a number from 1 to 15. Thus, to change the rate to 10, you would use something similar to:
1 setrate 10
The current rate setting is returned by the speech.rate variable. Thus, to print the current rate setting to the screen, you would use something similar to:
1 print speech.rate
Here are some important notes when dealing with speech controls.
• 1. You can use numeric variables to specify settings. Example:
1 setpitch x
Let x represent 3. The statement above will set the pitch setting to 3.
• 2. Changing the values of the s.pitch, s.freq, speech.rate, and speech.volume return variables will not affect the current setting, unless the value is changed by the setfreq, setvol, setpitch, and setrate statements.
• 3. You should always store the current default setting (the setting before you changed it,) in a numeric variable before changing the speech setting. This will prevent your speech settings from getting messed up. You can do this by assigning the appropriate values to some variables, like this:
This will make Y have the value of s.pitch in its current state, and the pitch value can be returned to default by:
For your homework, I want you to create a BASIC program that involves conversations. You can create a trivia if you want, which, if every time the user gets an answer right, says something in a different speech setting. Be sure to restore the user's default setting if you change it. Also, keep track of points and perform actions based on the value at the end of the game. For example:
if p < 1 print "you failed my trivia!"
Good luck! If possible, send me your game through email and I will post it on my site. Before you send me your game, however, you must agree to the BPCPrograms's policies and rules which you can view by
You can submit your program to:
We have discussed a lot in this manual so far, however there's always one thing missing!
Using some simple statements, you can create music in your program that is similar to a midi (.mid) file on a computer. In the following sections, we will discuss these statements.
(Please note that this chapter is not supported by the Millennium addition of the Braille Lite series. This is because the sound chip in the m20/40 was updated, and no longer supports this sound feature. If you attempt to run a program with sound on the m20/40, the system will hang up and freeze, therefore causing you to restart it.)
A fix around this problem:
If you have already created a program with sounds in it, and are attempting to run it on an m20/40, you will need to take out all sounds and bells. If necessary, you might want to release an "m" release of your program, which contains this modification.)
The first item we will discuss is the beep statement. This statement allows you to create a bell sound in your Blazie Note taker. You would use something similar to the following syntax to create this bell sound
1 beep:print "hi"
This statement first creates a bell sound in your program. Then it prints the word "hi."
(Note that the bell sound is similar to the "hourly announcement bell only" and "hourly announcement bell and voice" options in your system's status menu.)
You can create as many "beeps" as you want as long as it doesn't exceed the line limit. Next we will look at how to create music in the note taker.
Creating music in the Blazie Note taker through a BASIC program is pretty simple. To play a note, you must use the "sound" statement. Then you must have the note of hertz to play the sound at. Followed by a comma, you will have another argument. This argument specifies how long the program should "hold" the note being played. This number is in .1-second increments. The following example will play a musical note at the hertz 100 and hold it for 1 second.
1 sound 100,10
The word "sound" tells the interpreter that the program has been instructed to play a note. Then you have two numbers, with a comma to separate them. The number to the left of the comma, or the first number, is the number which specifies the note of hertz to play the sound at. The second number, or the number to the right of the comma, is the number which specifies how long the called note should be played. This is in .1-second increments. Therefore, if the second number is 20, the note will be played for two seconds.
The rnd function generates a number between 0 and 1. If the program is instructed to, it will take actions based on the outcome of the rnd result. (See Appendix 1 for a definition of a function.)
The rnd function must be attached to a nonnumeric variable in order for the program to determine what to do next based on the result of the rnd function, unless an equation is written straight out (see appendix 6.) A simple rnd function is shown below:
let x = rnd()
This tells the program to generate a number between 0 and 1, and substitute it for the variable x. Then you may have your if statements following the rnd function line. Example:
let x = rnd():if x = 0.05 then end
Since the rnd function generates a number between zero and one, its outcome will always be a decimal value. For example, it might result to 0.8785333.
This will cause confusion when using the rnd function, since we are not aware of what number it will generate. This problem can be solved by using the "int()" function.
The "int()" function removes all the numbers to the right of the decimal point. The number to modify must be placed in parentheses. For example, int(5.55879984) will return 5. This means that if you type the following, it will return 0.
Note that you may want to attach it to a variable.
let x = int(rnd())
However, the return result will always be 0. You can't do anything much with the result always being 0. Therefore, you will need to write an equation to have the rnd function generate something else besides 0. Say you want it to generate a number between one and five, type the following:
let h = 1+int(5*rnd())
Likewise, you can have it generate a number from 1 to 3.
let h = 1+int(3*rnd())
You can have the rnd function generate a number between 1 and any number as shown above. In order to have the number be a whole number, the int() function must be used.
When we discussed the rnd function, in some examples, two or sometimes three parentheses were used on the right side. Why is this so? In programming, you are required to "balance your scale." This means that if you have 2 left parenthesis in your equation, you must have 2 right parenthesis in the equation.
We discussed the int function. Since it has its own set of parentheses, and the rnd function has its own, when these two functions are used in conjunction, they create a total of 2 sets of parentheses in one equation. (A set refers to one left parenthesis and one right parenthesis. It can also be referred to as a pair.)
Here, we use both functions. Since both functions have a set of parentheses, we will have more than one set of parenthesis in our equation. The set for the int() function opens first. This calls for one left parenthesis.
Now we write our rnd function. Seeing this, the rnd function here is actually an argument for the int function. We now have:
Since the rnd function has its own set of parenthesis, we have:
Now we need to close both of the sets since we are done writing the arguments for each:
The common question that is asked at this point is "Why can't you just put int()rnd()?"
We can't do this because the rnd must be an argument of the int function, so the proper number is modified. Note: For a more thorough explanation on equations, see appendix 6.
The rnd function may sound complex, however it's not. The program below should give you a better understanding of the function, and you should be ready for your fourth homework assignment.
1 print "this is a test program."
2 'if i = 1, the program will print "hi" and so on
3 let i = 1+int(2*rnd())
4 if i = 1 then print "hi"
5 if i = 2 then print "c you."
This program uses the rnd function to command the program to print statements. Pretty simple, right?
I want you to create a program that will ask the user random questions. They can quit anytime. Also, if you want to make your program complex, you can keep track of which question they have answered and/or keep track of score. If the program lands on a question which they have already answered, have it jump back to where the program randomly picks a question.
Hint! This task will require the use of variables, duh, heheheh! You can't escape them! Good luck!
A while loop allows you to tell the program that as long as the given condition is true, to perform certain tasks. After the given condition is false, the program will skip the while loop and begin functioning just after it. For example, you can tell the program that as long as x is < 6, to say "less than" or something similar.
A while loop contains three parts
Open While Loop (while)
While Body (statements after while)
End While Loop (wend)
On one line, we simply have the word while followed by the condition to compare. On the next line are the statements and functions to perform as long as the condition specified above is true. Next, on a separate line, we simply have the word wend. This signals the end of the while loop. A simple while loop is shown below:
1 'the next line defines the start of a while loop
2 'it indicates that if test is < 6, to execute the body
3 'first, lets specify the test value
4 let test = 0
5 'now, our while loop starts
6 while test < 6
7 'this defines the start of the loop and, as long as test is less than
8 'six, the body, which is next, will function
9 let test = test+1
10 print test
11 'now, we end our loop
13 print "the statement is now false"
This loop causes the program to count to 6, then go to line 13.
As long as test is less than 6, 1 will be added to test and then the value will be printed. This, eventually, will lead to test being equal to or greater than 6. When this occurs, the while loop is false since we specified that only if test is less than 6 will the while loop execute. Now, since the loop is no longer true, it will be ignored and the line just after the wend will start to function.
The while loop can be helpful, but, if the right statements are not written, will cause the program to just sit there and do nothing. For example, in the above section we wrote a simple while loop. If we left out let test = test+1, the program will just keep saying "zero," until the program is terminated or the unit is restarted. This is because test is not being modified, so its value will not change and, by the let statement above the while, its default equivalent is zero so, if one is never added, it will remain less than six. This is why you should always read your while loops before compiling them. This will insure that it will function properly.
A for next loop is another type of loop. Unlike the while loop, this loop doesn't expect, let alone except comparisons. Instead, it uses a counter. This counter is a variable, which is called every time the loop executes. With a for next loop, you can execute a set of statements as many times as you like. There is no while ... <>= ... . The variable which is to be used for the counter is assigned a value. This value is the heart of the loop. It determines whether the loop should keep going and if so, for how long.
We will look at a simple for next loop below. Then, we'll discuss this loop.
1 'a basic setup of a for next loop is this
2 for a = 1 to 10
3 'like the while loop, this loop has a body
4 print "hello"
5 'and, we close the loop. A variable
6 'does not have to be used, but it's good for program tracking.
7 next a
8 'can simply read "next"
Now, what does this loop do? From the while loop, you may understand that this loop prints "hello". It's obvious, isn't it? What about the "for a = 1 to 10" and "next a"?
A for next loop is entered in the following order: for counterVariable = fromWhat to what. Therefore, the loop above uses A as its counter. For a = 1 to 10. The one to ten part of the loop specifies what the counter will start at. In this case, when the loop is executed, A will yield one. The loop will then execute as many times as it takes for A to yield 10.
This loop will print "hello" ten times. This is because when the loop starts, A yields one. When the program sees a "next" statement, it signals the end of the loop and the loop will restart if the counter has not yet reached ten. When it restarts, basically what happens is: counterVariable = counterVariable+1. This will happen until the ending number is reached which in this case is ten.
Since the counterVariable is a regular variable, it can be used.
for k = 5 to 8
y = k-1
There are exceptions to counterVariable = counterVariable+1. It can be changed to counterVariable = counterVariable+2, 3, Etc.
With the step statement, you can do some pretty weird stuff with loops. Your counter can count by 2, 3, Etc. You can also reverse the operation by setting your counter to count backwards. This is useful if you want to make a factorial program where every number multiplied is one less than the previous number until the number being multiplied is one. We will show you an example of this later. For now, we'll just deal with counting forward. The following loop will start from one and execute in the format: y = y+2. Therefore, the body will execute five times.
1 for y = 1 to 10 step 2
2 print "the y variable now yields "y"."
Notice the step statement. The loop starts out as we are used to seeing is: for y = 1 to 10. Then you see the step statement. Think of it like: counterVariable = counterVariable+... . After the step statement, you find the number two. Therefore, the loop now literally reads: for y = 1 to 10 y = y+2.
This will mean that the counter will count in terms of 1, 3, 5, 7, and 9. In order to have it count like 2, 4, 6, 8, 10, you need to start your loop at 2 instead of 1. The counter can also be reversed. I.E. 10 9 8 7 6... To accomplish this, you must use the step command. Simply insert a negative (-) sign in front of the argument. Step -1.
for y = 1 to 10 step -1
There is a major problem with this loop. It will function improperly because when y yields 1, the counter is told to: y = y-1. Y yields 1-1. Get the picture? This loop may simply terminate the program because the counter has returned a value which shouldn't have occurred. So how do we tell the counter to count backward?
What you have to do is reverse your loop. For y = 10 to 1 step -1. Makes sense? Since the loop is instructed to count from 10 to 1, it won't know what to do since it counts forward only. By using the step statement, we are telling it to count backward just like what happened above. However, this time the loop will execute properly because in literal form, the loop reads: y = 10 y = y-1..terminate when y = 1. In the previous loop, the literal form read something like: y = 1 y = y-1..terminate when y = 10. It doesn't make sense at all, does it?
Now, to demonstrate a good use of the for next loop in conjunction with a step statement, I've put together this little factorial program. If you pay attention in class, you know that a factorial is entered in the following manner: x*x-1*x-2*x-3... We can make a program find a factorial for us. Note carefully the for next loop and the use of its counter.
1 input"enter factorial",factorial
3 if fact>18 then ?"your factorial of "fact" may not return an answer because of its value over 18."
4 for x=factorial to 1 step -1
5 if x=factorial then x=x-1
7 ?factorial"& = "fact
Please note carefully the spacing. Between operators and such, spacing is not required. Also, instead of typing "print" hundreds of times, you may just type a question mark (?). This saves a lot of time. (Refer to appendix 5 for further details.)
A nested for next loop is a loop inside another one. You may be wondering why such a thing exists. It is useful especially if you're trying to set up a grid in a multi-dimensioned array. For a discussion of arrays, see section 28. To start off, the program below is an example of a nested loop. Note that you must include the appropriate variable when nesting loops.
1 for LoopOne = 1 to 10
2 for LoopTwo = 1 to 10
3 print "The first loop is now at "LoopOne" and the second loop is at "LoopTwo
4 next LoopTwo
5 next LoopOne
Notice how the for next loop which used LoopTwo as its counter was terminated first before loopOne. This is because loopTwo was nested inside loopOne. A more sensible example would be a baby and a cradle. You put the baby in the cradle, not the cradle on the baby. And, you can't let the baby's feet, hands, or any other part of its body hang outside the cradle or the baby will get hurt since it's so fragile. Similarly, you can't put a nested loop ouside its parent loop or the program may crash. Now, what does this program actually do? First, it starts the loop which uses LoopOne as its counter. While loopOne is executing, is executes loopTwo since loopTwo is part of the body of LoopOne. Once it loops LoopTwo 10 times like it's supposed to, it continues executing the rest of the body of loopOne. And then it finds the next statements telling it to start over. So, you actually have two loops executing simultaneously. Notice that the next statement must be accompanyed by its loop's respective counter variable. You can't, unlike single-leveled loops, leave out the variable.
The program above will display messages in the following manner: LoopOne is now at1 and loopTwo is now at1
LoopOne is now at1 and LoopTwo is now at2
This will continue until loopTwo reaches 10. When this happens, the first message after this event will display: LoopOne is now at2 and loopTwo is now at1
For further clarification, copy and compile the following program:
1 for i=1 to 10:for j=1 to 15
2 print i","j
3 next j:next i
Notice how the messages are displayed. This should give you an idea of how to apply nested loops to multi-dimensioned arrays.
Say, for instance, we wanted to set up a 3x3 grid, with every square (element) holding a number 5. Obviously, we would need to set up a multi-dimensioned array like this: dim grid(3,3,3)
We can now fill in the 5's like this:
1 dim grid(3,3,3)
Setting up a grid like the example above can be very time consuming, and in some cases confusing. We could easily get lost in our grid when handling the definitions like it was shown above. With nested for next loops, however, we can literally automate the task of setting up the grid. Before we actually dive into the program and create it, copy and compile the following program. This will give you an idea of how this task will execute:
1 for a=1 to 3:for b=1 to 3:for c=1 to 3
2 'the next statement will show you the pattern in which it's going to loop
3 print a","b","c
4 next c:next b:next a
Notice how the loops execute. A whole round of loop C is only one round of loop B. Similarly, a whole round of loop B is only one round of loop A. Considering this program, our task could be accomplished through the following program:
1 dim grid(3,3,3) 'sets up our grid
2 for a=1 to 3:for b=1 to 3:for c=1 to 3
3 'now we have 3 loops, with A being the parent loop
4 grid(a,b,c)=5 'we now specify our array values
5 next c:next b:next a 'we then terminate all loops
If this section is a bit foggy to you, please don't hesitate to Email me with your question(s.)
From the program above, you can see that nested loops will come in handy if you are wanting to create a grid type of game such as Chess.
Your homework is to interpret the program shown in section 25.1 (the factorial program). Email me the literal concept of this program just like I have literalized the for loop programs for better understanding. Note if you do not have access to Email use someone else's computer to mail me. I will reply you and give a rating on your response. Good luck!
In basic programming, and in all other programming languages, a line can either contain a statement, variable definition, or a function. We've seen examples of statements and variable definitions, however we've looked at functions briefly, but haven't spent time with them. In this section, we'll look at functions in depth.
Note: For a list of all functions and a brief description of each, see the BASIC Interpreter's User Manual at: ftp://ftp4.freedomscientific.com/public/basic/basic.txt.
A statement will do the same thing unless you change its code. For example, "get y$" will always get a keystroke and put it in y$, unless the code is changed to something like: "input a$" or "get name". A function, however, is a different aspect. It performs its task as usual, but tells the program what it gets based on its arguments, or parameters. An argument is the revolving point, or heart of a function. The value the function returns is based on its arguments, if it accepts them. Some functions don't except arguments. However, these functions also don't always return the same value. For example, we learned earlier that s.pitch returns the current pitch setting. The s.pitch function will not always return the same value. It may return one, two, Etc.
Having this said, a function is a command, which returns a value. Based on this value, you may have a set of if...then...else... statements. Next, we will look at a format of a function.
If a function accepts arguments, the arguments must be enclosed in parentheses. The function abs() returns the absolute value of a number. Therefore, to get the absolute value of -5, you would use abs(-5). Likewise, to return the absolute value of a variable called Y, you would use: abs(y).
If a function needs more than one argument, a comma must separate the arguments. For example, the left$(,) function chops off the left part of a string. Obviously, it's going to need two arguments. First, it will need the string from which to chop the left part of. Next, it will need the number of leftmost characters to chop from that string. Therefore, to chop two characters from the string contained in y$, the following syntax would be used:
Likewise, to chop two characters from the string "hello", the following syntax would be used:
This function will return "llo".
An array is one of the most useful elements in BASIC programming. Through the use of arrays, one variable can hold multiple strings, or values. Take note that array variables are type-sensitive, just like all other variables. To create an array variable, use the syntax: dim varName$(dimDef).
The word dim signals an array definition. Dim stands for dimensions. This will get clearer as we move on.
Next comes varName or varName$. VarName can hold numbers only, and varName$ is intended for strings. VarName, in either case, is the variable name which will contain an array. For the heck of it, lets name ours test$.
Next, in parens, you see dimDef. For now, we'll stick with one-level array definitions. Think of an array as graph paper. Each little square is an array element and holds its own value. Each row is a level, starting from row one (level one.) Our array is going to have one row, therefore making it a one-leveled or one-row, also known as: one dimension deep. The number of squares from top to bottom depends on what level your array is set to. The number of horizontal squares *each row* has depends on the number of squares given to that row. Each row is defined separately. Lets make our array one-leveled, so we can start from the beginning:
The 5 in parens gives us one row, with 5 squares, or elements. Our array can now hold 5 values, strings, at a time. Think of every element as a separate variable. To assign a value to an array element, use the syntax: test$(1)="element one".
Notice that before a value is assigned, we need to tell the program what variable we are referring to. Next, we tell the program the exact element location in that variable to which we want to assign a value to, surrounding the element position in parens. After this, you see the regular continuation of assigning values. The first square in the test$ one-row array variable is now shaded with "element one".
To display this value, treat it like a variable. When referring to an array variable, it is mandatory to specify the element position. Thus, to display "element one," consider the syntax: ?test$(1) (see appendix 5 for format clarifications.)
Numeric arrays can also be used: test(5). These elements must be numerical values.
This gives the third element in the test array a value of 22. Numerical array element(s) can, like numeric variables, be used in expressions, functions, and yes, variables.
This returns 27.
A multi-dimensioned array has more than one level of elements. Here, the number of elements each level contains must be separated by a comma. Dim test$(5,2,8) sets up a test$ array which is three dimensions deep. The first dimension, or level, has the ability to except 1-5 element specifier numbers. This will make more sense later on. The second dimension has the ability to except 1-2 as its element specifier, and the third dimension has the ability to except 1-8 as its element specifier. So what's all this rubbish about element specifiers? Look at the program below. Notice that when referring to multi-dimensioned arrays, all dimensions must be filled in.:
1 dim test$(5,2,8)
Notice that each level must be filled out. In the next section, arrays will get clearer.
In section 28.1, our array read: test$(5,2,8). Therefore, the following code is an example of an illegal array call and will return an "array access error.": test$(6,3,9). Notice here that the element specifiers (the numbers associated with the commas (5,2,8)) are exceeding their limits. We specified that the first dimension can only contain a number from 1-5, the second can only contain a number from 1-2, and the third from 1-8. Therefore, the example shown recently is an illegal syntax. An example of a legal array call would be: test$(2,1,5). Now that we understand the number system, lets get back to the concept of arrays.
The code: test$(3,2,3)="hi" says that in the position 3,2,3 of this array grid, we'll place "hi." In other words, the array definition: dim test$(2,2,2) can have values in the following places:
There may be more, and if there are, which I doubt, but then again I'm not the greatest problem solver, I'm not going to sit here and name them all! This example alone should have clarified everything.
• Multi-dimensioned arrays can be up to 10 dimensions deep: test$(2,2,2,2,2,2,2,2,2,2)
• Variables and functions can be used to reference arrays, but not when defining them.: ?test$(abs(10))
• Arrays can be used to create menus. (Note: use in conjunction with while loops.):
1 dim t$(2)
2 t$(1)="item one":t$(2)="item two"
3 while key$<>"e"
4 get key$
5 if key$="b" then x=x-1 'if the user wanted prior choice
6 if key$="f" then x=x+1 'if the user wanted next choice
7 if x>2 then x=1 'if the user reached end of menu, wrap to top
8 if x<1 then x=2 'if the user reached top of menu, wrap to bottom
9 if key$="e" then ?"you selected the option "t$(x) 'if user selected
option 10 wend
This is just one of many uses of arrays.
• It is sometimes best to stick with one-leveled arrays instead of multi-dimensioned arrays.
Note: chapters 29-30 were written by a BPC member, Graham Pearce. To drop him an email, visit the BPC Team List Page, and dig out his email address.
We have already seen that you can assign elements in an array like this:
But what if we've got lots of elements to assign this way? If you've got more than about five or six elements to assign, you could easily lose track of what element you are assigning them to, and cause unnecessary errors. One way to assign elements is to use the data and read statements. The syntax is like this:
Or data "string1","string2","string3"
You do not have to enclose the strings in quotation marks, but it's good practice, and will make your source code more readable. Examples:
Defines three numeric constants as being 1, 3, and 4. You can assign these to variables later on.
Defines three strings as being apples, peaches, and strawberries. In the next section, you will learn how to attach variables to these strings.
The statement data "apples","peaches","strawberries" is useless on it's own because there is no way the program can interact with the strings defined in the data statements until you've assigned variables to them. This is where the read statement comes in handy.
The syntax is:
Or read variableName1,variableName2,variableName3
You can also set your read statements out like this, assuming you've defined the dimensions for the array first. Example:
5 dim fruit$(3)
10 data "apples","peaches","strawberries"
20 for i=1 to 3:read fruit$(i):next
This is like saying:
Except it's a lot easier to write and more efficient too. How about assigning the constants defined by the data statements into multi-dimensional arrays? Sure thing. Here's one way you can do it.
5 dim square$(2,2)
10 data "lower left","lower right","upper left","upper right"
20 for i=1 to 2:for j=1 to 2:read square$(i,j):next j:next i
This is like:
square$(1,1)="lower left":square$(1,2)="lower right" ... And so on.
Your data statements do not need to be before your read statements. They can even be at the end of the program! The following example is acceptable:
10 read p,q,r
20 print r" "q" "p
30 data 98,24,54
This will display 54, 24 then 98.
One last note. Be sure that the variable type you want to read is the same as the variable type that's in the data statement. The following example is incorrect:
5 data "the devil",666,"hell"
10 read n,d$,h$
The following is one possibility of a correct statement in line 10:
10 read d$,n,h$
This statement is used more often in artificial intelligence programs and stuff like that, but it's worth noting here. If you want to make it so that the read statement accesses the first constant defined in the data statement again, you can do it with the rewind statement. Here is an example.
10 data "testing,"1 2 3"
20 read a$:rewind:read b$,c$
30 print a$" "b$" "c$
This will display testing testing 1 2 3.
Design a game with the specifications outlined below. You can extend on this, but this is the bare minimum.
You are lost in a maze with a minimum of 4 rooms in it. The object of the game is to find the treasure hidden in the maze. Once you have done that, you must find the exit.
The treasure must be hidden in a random room each time, but it cannot be at the entrance. The exit may or may not be a random location. It's up to you.
You must navigate the maze using the compass directions north, south, east and west. The game must tell you where the exits are in each room, and the game also must tell you when you've found the treasure, and in what direction the exit is if you're one room away from it.
Hint: Give the exit a particular room number which is higher than the highest room number in the maze itself. That way, before the game asks for your move, you can get the computer to check whether the player has gone through the exit or not.
This chapter will cover modifying strings and extracting parts from them. (Chapter written by Graham Pearce.)
We already know that if you type a statement like input n$, we can type a series of letters and/or numbers and press return, and then these letters and/or numbers will be evaluated. But what if you want to evaluate only the first four letters of what the user typed? You could tell the user to type only four letters, but there is know way of knowing whether he/she will follow this instruction. The easiest full-proof way is to use the left$ statement, which has the following syntax:
Variable refers to the variable name, and position refers to the number of characters to the right will be looked at. For example:
20 print left$(t$,3)
This program will cause the word 'the' to be spoken.
Similarly, we can use the right$ function to just evaluate a number of characters starting from the right of the variable. The syntax is the same as the left$ function, but it does the reverse. For example:
10 t$="therein":print right$(t$,4)
This program will cause the word 'rein' to be spoken.
The mid$ function is a bit more complex than the left$ and right$ functions. It allows you to take a part of a string from the middle. It's syntax is:
Where variable refers to the variable name, position1 refers to the number of characters from the left to start reading, and position2 refers to the number of characters to read. For example:
10 t$="therein":print mid$(t$,2,4)
This program will say 'here'.
The len function will compute the length of a string. For example:
10 f$="four":print len(f$)
This program will say the number 4, because that's how many letters there are in the word four.
Instead of always using a number for the position indicators in the function, like the second argument in left$. For example:
10 input "enter a number less than 53.",p
20 if p>52 then 10
30 print left$(a$,p)
This program sets a$ to have the alphabet written both backwards and forwards. It then asks you to enter a number less than 53. The number must be less than 53 because there are only 52 characters in the string a$. It then prints the first p letters of the string a$. For example, if you typed 3, the program would say abc.
I want you to create a program that asks you to enter a sentence of up to 80 characters long. This program should then search for the occurance of your first name, and if it finds it, it should say "that's my name, don't ware it out!" or something to that effect. If your name was Adam, and you typed 'Douglas Adams writes books', the program should respond with that's my name, don't wear it out. However, if the user types in something like 'I'm visiting a dam today', it should not respond with that. Hint: Look in the source code for the text adventures at: www.anycities.com/graham43/basic.html. In fact, that may be too obvious ...
The following is a list of terms and words used when programming in BASIC.
Argument: A term which refers to the statements which make a function perform. The arguments of the functions must be enclosed in parentheses. The parentheses must be balanced on each side of the equation
BASIC programming: a programming language, popular in the 80's, which is a good introduction to computer programming
Call: a phrase referring to commanding or creating a statement or function
Compile: a term referring to turning a source into an actual program. Sometimes interpreters can simply run the program's source, however for most interpreters, a compiled version of the source is required
Compiler: the program used to compile the source file
Constant: An element which is similar to a variable, with the exception that it holds a CONSTANT value, whereas a value of a variable can change during program run-time
Equation: a function or operation, which solves a given argument set. The operators which are used to signify mathematical equations include, but are not limited to: + - * or /
Execute: running the compiled program through an interpreter. Putting the program in action to perform its tasks
Function: a call, which returns a value. If a function accepts arguments or parameters, the parameters must be enclosed in parentheses
Interpreter: the program used to run or execute the compiled version of the source file
Reference point: another term for line numbers or type of reference used in the program
source: the statements which make up the program
Statement: a command which causes the program to function and react. Statements do not return values unlike functions. Instead, they perform actions such as print a word, or get a keystroke
String: a term referring to a series of characters and/or numbers.
Telecommunication: a type of connection either electronically or by waves which allows one device to communicate to another device or remote device
Value: the return result of a function or equation. The current amount of a variable
Variable: a character or word, which holds a value. Variables which hold a character string must be followed by a dollar sign
Yield: the same as equal or equals I.E. a yields one. a equals one
Throughout this manual, we were given homework assignments, which required us to create a program. To do this, we must compile our source, then execute it. This appendix discusses how to perform this task.
In order to compile/run a BASIC program, you must have the run.bns and compile.bns utilities in your unit. (See section 2 for information on acquiring these utilities.)
Your source is held most commonly in a *.src file. If you saved it in a file other than *.src, you will need to provide your file extension when compiling.
To compile a source file, start the compile.bns utility. (Refer to some other reference on running utilities.) When asked for the name of the source file, type the file name which your source is stored in. (Note that if you have an extension of *.src, you do not have to type the full file name. However, if your source is stored in a file other than *.src, you are required to type the full file name.)
Press e-cord/enter when the file has been typed into the field provided. The utility will confirm "compiling," and you should hear progress clicks while the source is being compiled. Once the source has been successfully compiled, the compiler will create a *.bas file in your unit. This is the file that can be run to access your program.
To run a *.bas file, start the run.bns utility. When asked for the program to run, type in the file name of the *.bas file you want to run, and press e-cord/enter. The program will begin to execute. (Note that pressing z-cord/escape while a program is being executed will terminate the execution. This is useful for large programs.)
Note that you can minimize the amount of keystrokes pressed to execute a BASIC program. You can either create a macro, which we won't get into, or you can type the file name to compile/run as an argument. An example would be typing "compile test.src" without the quotes. This will compile the source test.src without having you go into the program and instruct it to do so yourself. This goes the same with the run.bns utility. Simply type "run xxx" where xxx is the file name of the program you want to execute.
There is one more important note when executing a program. Large programs (5 pages or more,) will take a long time to execute and start. You may have to wait more than 30 seconds for a 13 page *.bas file to start. In a program this large, you may experience occasional malfunctions or hang-ups in your system. These hang ups should not damage/crash your system, and usually a restart gets your unit going again.
Sometimes, but not often, the program compiles correctly but interpretation fails. In this case, try recompiling your program. If that doesn't solve it, your compile/run utilities may be damaged and cause false interpretation/compilation. If this is the case, redownload the two utilities and try recompiling your source then running it. If the interpretation fails yet again, contact an official for help. A copy of your source may be required for them to solve your problem.
Once you create a program on your Blazie Note taker, you can also run it on a
PC. Unfortunately, the program, for right now, can only be run in DOS mode.
To run a program on a PC, you must have the GWBasic interpreter on your PC. This
interpreter is a DOS program, so installation is not required. You can download
the GWBasic interpreter from the following location:
Unzip it and read on to learn how to run your program. The source file will be required.
You must modify some of your source for it to interpret correctly in GWBasic.
1. Remove all synthesizer controls from your program. You must also remove the following values for the removed statements, including variables. If you have any statements which effect the controls, remove them as well. For example:
print "your current setting is "s.pitch". type this number and press enter."
2. You must modify your "get" statements since this is specific to the Blazie Note takers and is not understood by GWBasic. Replace all get statements by following the example below:
If you have the statement: 200 get namecon$, you would replace it with the following statement:
3. All sounds with frequencies less than 37 must be removed. This is because the GWBasic interpreter can't send a sound that low, so you might want to change it to something higher or just altogether remove it from your program.
4. The fprint and finput statements must be modified. Instead of fprint 2,"hi", for example, we should have print#2,"hi". Instead of finput 1,c$, we should have input#1,c$.
5. If you use open or create statements, you must change them depending on what the file is opened for. For example, if all you used was fprint#1 statements, and the filename was myfile.myf, you would type something like: open "myfile.mif" for output as 1 If it was just being used for input, like finput#1,d$, you would use: open "myfile.mif" for input as 1
6. If you have your else statement on a separate line surrounded by nothing else, remove the else keyword and leave the rest of the statement on the line. You have to do this because of the way gwbasic interprets if-then-else statements.
7. Change all instances of rnd() to rnd(1).
8. If the program uses random numbers, put the following statement at the very beginning:
This randomizes the random number generator according to the clock on the pc. This is not required on the braille lite.
9. If the program on the blazie notetaker uses statements to do with the time and date, convert them as follows:
10. If you encounter the rewind statement, change it to restore.
11. If you encounter a statement like if d=0 goto 5, change it to if d=0 then goto 5. In fact, you should leave the then keyword in there, because it makes the source code more readable.
12. If the rhythm of the sounds really matters in your program, multiply the length of the sound by 1.82. This is needed because gwbasic works in clock ticks, which occur 18.2 times per second.
13. If you need functionality with windows screen readers, place cls statements in the program to clear the screen. Find out where to put these statements by trial and error.
Once these modifications are made, it's time to run your program using GWBasic!
1. Upload your program on to the PC either by copying it to a disk, or directly
connecting your unit through a telecommunications program. (Refer to the Blazie
manual for detailed information on this topic. (You must upload your source file
since this is what GWBasic will interpret. Running the *.bas file will cause
2. Once uploaded, open the GWBasic folder and activate gwbasic.exe. (If you are using a screen reader, you will need to use your mouse keys to review the GWBasic screen.)
3. In the field provided, type run "x" where x is the *full* path and file name of the file you want to execute. (In this case, you would execute your *.src or source file you just uploaded.)
The file should begin to execute. If you need more detailed information on running programs in GWBasic, refer to: the BPCPrograms homepage.
In BASIC programming, there's always more than one way to perform the same task. These ways are classified into two groups: the shortcut and the long way. If statements are no exception to this fact. You can write a lot of if statements and spend a majority of your time on them, or, you can write at least two ifs and eliminate all the other ones. This appendix specifies the various ways to write if statements. Although all the combinations are not included, this appendix will give you a general idea of combined comparisons, and you can combine your own by learning how to do it.
This appendix is organized in the following way:
First, there will be a sample if associated with the information below it. Below this statement, in the same paragraph, will be the description for the associated if statement.
if x = 5 then goto 400
If x is equal to 5, the program will jump to and begin executing at line 400.
if x < 5 then goto 400
If x is less than 5, the program will jump to line 400.
if x > 5 then goto 400
If x is greater than 5, the program will jump to line 400.
Note that after the if statement, you don't need to have the word "goto." Therefore,
if x < 5 then 400
is the same as
if x < 5 then goto 400.
if x = 5 or y = 6 then 400
If x is equal to 5 or y is equal to 6, the program will jump to line 400.
if x >= 5 then 400
If x is greater than or equal to 5, the program will jump to line 400.
if x <= 5 then 400
If x is less than or equal to 5, the program will jump to line 400.
if x <> 5 then 400
If x, in no way whatsoever is equal to 5, the program will go to line 400.
From the paragraphs above, you can see that there are many ways to write the if statements. Do not forget to include your else statement in the case of the if statements being false.
This appendix contains hints, tips, as well as shortcuts and notes pertaining to BASIC programming.
Between operators, spacing is not required. Example:
if x<5 then ?"hi"
The print statement allows text to be written to the screen. For example: print"hello" prints the word hello. When printing variables, the variable must not be enclosed in quotation marks or the program will interpret it as text. For example: print x prints the value of x to the screen. The print statement will except multiple arguments: print"hi"x
Assume x yields 2. This statement, when interpreted, will print "hi2". In order to put a space between hi and 2, the following syntax would be used: print"hi "x. You may also write: print"hi "x". hello "y".". This will print "hi 2. hello 5.", assuming x yields 2 and y yields 5. In replacement of the print statement, a question mark (?(Shift+/(1-4-5-6))) may be used. ?"hi". ?x.
An input statement may be treated like a "prompt box". Instead of printing the prompt before the input field is active, you may print it right when the input statement is activated. To do this, use the following syntax: input"prompt",pro$. When the program sees the input statement, it will print"prompt". The text the user types will be stored in pro$. This statement can also be written as:
Line numbers can range anywhere from 1 to 65535. Any line numbers outside these boundaries will cause the compiler or interpreter to detect false errors.
If a line number is out of place, the program may freeze, or in some cases return a "no such line number in line X". This is why it is important to check your line numbering before compiling a program, or you will be looking for an error which doesn't exist!
The word "let" is not needed when creating variable definitions. Let y=3 can also be written as y=3.
You may insert more than one command per line. This is accomplished simply by placing a colon (:) between the statements, acting like a divider.
A goto statement will not accept variables as its arguments.
The compile.bns and run.bns utilities for some unknown reason don't know the "on" statement, except when it comes to on error. Therefore, instead of entering:
on sn goto 100,200,300
you would have to type:
if sn=1 then 100
if sn=2 then 200
if sn=3 then 300
This appendix was written for the fact that RND functions were discussed, and some elements needed to be clarified. The discussion on the rnd function, unfortunately, left several gaps, and reviewing my Email, I was forced to include this appendix.
When you have thoroughly read this appendix, you can say that programming is like repeating 9th and 10th grade. One could say that it's Algebra. It is true that programming consists of inequalities (mostly if...then statements,) and variable expressions. The actual concept of expressions and/or equations is quite similar to, if not, a replica of Algebra.
On the discussion of the rnd functions and balancing scales discussed in sections 21-21.1, I failed to clarify equations. If you've been through, or are in Algebra, this concept should be fairly simple to grasp. First off, we'll discuss what is contained in equations such as variables, rules, Etc. After this, we'll discuss grouping and changing the way your equation is evaluated, or solved.
Before we begin, I'd like to share something which really got me in Algebra. I always used to get nailed because I simply didn't understand that an equation is a mathematical sentence which holds an inequality, and an expression is simply the mathematical sentence with no inequality. Doesn't make sense? Don't worry about it. An example of an equation is: 5+5=10, and an expression is: 5+5. Considering this, if statements are simply inequalities which are either proven true or false. So what's this got to do with programming? It is in no way important, and you won't get an F for not knowing it. It's just some side information so you know what's going on.
Maybe it was just because I didn't clarify it, but my readers don't think that functions and variables can go into expressions. They can, and we'll discuss them here. Lets refer back to section 21. The mathematical expression 1+int(5*rnd()) contains two functions. The int() and rnd(), both returning a numerical value. Since 5*rnd() will return a number from 0.x to 4.x, we int() out all the decimal values. Once that is done, we add 1 to the outcome of int(5*rnd()), seeing that we don't want 0 and we want it, if possible, to yield 5. Lets take a more simple example.
The abs() function returns the absolute value of its argument. Thus, abs(10) yields 10. The interpreter knows, and applies, the common order of operation. Some people refer to it as "Please excuse my dear Aunt Sally." This means that the program will evaluate parens first, followed by exponents, multiply/divide (depending on their order from left to right,) and finally add/subtract (depending on their order from left to right.) seeing this, the expression abs(10)+5/2 will return 12.5. First, the program will evaluate 5/2 which returns 2.5. Then it adds 10 (since abs(10) yields 10,) and the expression yields 12.5.
Look at the expression: 5+(x/2). Assume X yields 2. When the program looks at any expression, it says: "Hmmm... lets see... are there any parentheses?" The program will do what's in parentheses first. Therefore, it will first evaluate x/2, which yields 1. Then it will add 5 to 1, and get 6, which is the correct answer, by the way. Taking this information into account, it may sometimes be necessary to have multiple sets of parentheses if you are wanting to switch the evaluation order around. For instance, you may want subtraction done before division.
This expression yields 0. However, if we were to remove the parentheses, the expression would yield 16.
Wow! The important thing to note, first off, is the tilde (~) sign. This means "to the power of". The interpreter will always do first the element which is deepest into the parentheses, in this case x~3, which is 8. Then it will evaluate x/2*8+8, which is 16, assuming X yields 2. After this, it will add 5 to 16, which yields 21. You may also throw in some complex expressions, having multiple variables and functions. We won't discuss the following example, but just to give you an idea of what you can do, I've thrown it in.
Note that if...then comparisons can also be made up of expressions, oops, equations! If statements do contain inequalities, so they're equations. Check out the following if...then statement:
if 5+(8*3)>x then ?"test"
This equation does what it says. If 29 is greater than X, ?"test". Pure Algebra is what programming is!
This appendix documents the operators used in the expressions you will or may write in your programs.
/: Divided by
*: Multiplied by or times
~: To the power of, used to represent exponents
I noticed that a topic, printing text to the screen, was not covered in detail (brief discussion found in appendix 5.) For this reason, I have written this appendix. We will discuss the issue of displaying text to the screen.
To display text to the screen which is readable by the user, one must take advantage of the "print" statement. The basic syntax for a print statement is: print "text to be displayed". Notice that the text the author wishes to be displayed is surrounded in quotation marks. The example shown here will display "text to be displayed", without the quotation marks, of course.
Note: Since quotation marks are used to begin and end display messages, and some programs contain conversation which, of course, in proper writing is surrounded by quotation marks, the apostrophe must be used for the conversation bit.
print "'Hello?' he asks into the phone."
The next appendix will discuss more advanced uses of the print statement.
The print statement can display expression results and functions. If you are displaying a function or variable, consider the print statement no exception to this rule: the function, variable, or expression must not be enclosed in quotation marks. The following command will print the word "llo": print left$("hello",2)
Likewise, the following command will print the number 3: print 6-3
If an expression is passed to the print statement, the expression will be evaluated and its result will be displayed. Anytime a function, expression, or variable is passed to the print statement, it will be evaluated and the result printed to the screen (viewable text.)
You can, in the print statement, run text together. For instance, you can display: The variable y = [the value of y].
This is called passing multiple arguments to the print statement. Check out the program below:
2 print"X now = "x
3 'will display: X now = 5
When doing this, keep in mind one important rule, and you shouldn't have a mess of quotation marks: standard text is surrounded by quotation marks; this includes spaces. Non-standard text I.E., functions, variables, and expressions must not be enclosed in quotation marks. Check out the following program:
2 print"X now yields x"
3 'will display: X now yields x
4 print "X now yields "x
5 'will display: X now yields 5
6 print"x now yields"x
7 'will display: X now yields5
8 print "X now yields "x"."
9 'will display: X now yields 5.
From this example, you can make a conclusion that in BASIC programming, syntax is very important. This is, in fact, true for all programming languages. If the proper syntax is not followed, negative results will occur.
Run.bns · Compile.bns · GWBasic · A listof all statements and functions and a brief description of each.
If you feel that any chapter and/or section needs to be revised, please don't hesitate to let me know. I have written this manual to benefit others, and the only way I'll know if a chapter is not explained properly is if I'm notified by my readers.
Email: [email protected]
Direct link to BPCPrograms, Inc. page: http://www.anycities.com/mun0009/programs/
Latest copy of BASIC manual: HTML
MSN: [email protected]