Qbasic/Full Book View

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search

Contents


[edit]

Text Output

Text Output

[edit] Print

The text output command is PRINT. This is the command that we will be exploring through this section. PRINT takes a series of arguments. What that means is that in QBasic, after typing PRINT (note, for a short cut, just type a question mark '?') a programmer types the things he wants displayed and PRINT will display them. The first program will display the words "Hello World" on the screen.

PRINT [Text to screen]

[edit] 1HELLO.BAS

 PRINT "Hello World"

[edit] Understanding 1HELLO.BAS

First, copy everything (in this case, one line, but later programs will be much longer) into a text editor or into QBasic itself and save it as '1HELLO.BAS'. Next open it in QBasic (if you are not already there) and press F5. This will run the program. A black screen with the words "Hello World" in white in the upper left corner should appear. This is your first QBasic program. Now, Press F5 again. Now there should be 2 lines saying "Hello World". This is because QBasic does not clear the screen every time a program is run. To change this we will use the command CLS, which stands for CLear Screen. We will be looking at some other new concepts in the next program as well.

[edit] 2HELLO.BAS

 PRINT "This line will be erased"
 CLS
 PRINT "Hello";
 PRINT " World",
 PRINT "Hello Jupiter"
 PRINT "Good Bye",,"For";" Now"
 PRINT 1,2,3,4,5

[edit] Commas and Semicolons in PRINT and CLS

Addressing 2HELLO.BAS in line order, the first line prints "This line will be erased." to the screen, but in the second line, the CLS command clears the screen immediately after, so it will not be seen (technically it flashes at the bottom form columns. "Hello Jupiter" should line up with '2' at the bottom. More than one comma can be used in a row. In this example, after "Good Bye" two commas are used to move "For Now" over two tab columns. "For Now" should line up with '3'.

My final statement on this topic is to play around with it. Try using commas and semicolons in a program.

[edit] 3HELLO.BAS

 CLS
 hello$="Hello World"
 number=12
 PRINT hello$, number

[edit] Variables

Variables are used to store information. They are like containers. You can put information in them and later change the information to something else. In this first example they may not seem very useful but in the next section (Input) they will become very useful.

In this example we use two types of variables - string variables and numeric variables. A string variable holds words, a string of characters (a character is a number, letter or symbol). In this case the characters are letters. A string variable is denoted by ending the name of the variable with a dollar sign. The string variable in this program is hello$. What ever you set hello$ equal to will be displayed in the PRINT statement. The numeric variable is number. Numeric variables do not have a special ending like string variables.

[edit] 4FACE.BAS

 LOCATE 14, 34     'position the left eye
 PRINT "<=>"       'draw the left eye
 LOCATE 14, 43     'position the right eye
 PRINT "<=>"       'draw the right eye
 LOCATE 16, 39     'position the nose
 PRINT "o|o"       'draw the nose
 LOCATE 18, 36     'position the mouth
 PRINT "\_______/" 'draw the mouth
 LOCATE 19, 42     'the bottom
 PRINT "The Face by QBasic"

[edit] Locate statement

Locate allows you to position the cursor for the next piece of text output. Contrary to cartesian coordinates which read (X,Y), the locate statement is LOCATE Y,X. In this case Y is the distance down from the top of the screen and X is the distance from the left side of the screen. The reason that LOCATE does not follow the standard coordinate system is that it is not necessary to include the X portion, you can use the format LOCATE Y which just specifies the line to start on.

[edit] 5FACE.BAS

 CLS
 
 LOCATE 14, 34
 COLOR 9
 PRINT "<=>"
 
 LOCATE 14, 43
 PRINT "<=>"
 
 COLOR 11
 LOCATE 16, 39
 PRINT "o|o"
 
 COLOR 4
 LOCATE 18, 36
 PRINT "\_______/"
 
 COLOR 20
 LOCATE 19, 42
 PRINT "U"
 
 LOCATE 1, 1
 COLOR 16, 1
 PRINT "Hello World"

[edit] Colors

The program 5FACE.BAS is broken into sections to make it easier to read. This is an example of a good programing habit. Each three line piece of code each piece of code specifies what color it's part of the face should be, where it should be and what it should look like. The order of the position and the color is unimportant. The new statement COLOR allows you to change the color of the text. Once changed, all output will be in the new color until COLOR or CLS is used. The format for the COLOR statement is:
COLOR [foreground]
or
COLOR [foreground],[background]
The colors are designated by numbers which will be discussed in the next section.

[edit] Color by Number

There are 16 colors, numbered from 0 to 15.

0 Black 8 Dark Grey (Light Black)
1 Blue 9 Light Blue
2 Green 10 Light Green
3 Sky Blue 11 Light Sky Blue
4 Red 12 Light Red
5 Purple 13 Light Purple
6 Brown/Orange 14 Yellow (Light Orange)
7 Light Grey (White) 15 White (Light White)

If you look carefully at this chart you can see that there are 8 main colors (0 through 7) and then those colors repeat, each in a lighter shade. You may also notice that the colours act as a combination of binary values (where blue=1, green=2, red=4, etc.) This makes it much easier to memorize the color scheme. Blinking colors are also available: at 16, the colors start over again with blinking black and extend through 31 (blinking white). However, the blinking option is not available for the background, only for the text (foreground).

It is possible to switch the blinking foreground text with an intense background, but this task is beyond the scope of the QBasic textbook, and may not work when Windows displays the console in windowed mode.

[edit] Summary

In this section we looked at several methods to manipulate output. All centered around the PRINT statement. LOCATE and COLOR modified where the text was displayed and how it looked. We used CLS to clear the screen. There was also a basic introduction to variables which will be expanded upon in later sections.

[edit]

Basic Input

The INPUT command is used to gather input from the user. This section will attempt to teach you how to gather input upon request from the user. For real-time input, see QBasic/Advanced Input.

Here is the syntax of the input command:

INPUT "[text to user]"; [variable] ' Prints questionmark before prompt
or
INPUT "[text to user]", [variable] ' No additional question mark

Example:

INPUT "What is your name"; NAME$

When an semicolon (;) is used between the text to the user and the variable a question mark and a space is added. When a comma (,) is used no question mark is added.

The stored variable can now be used in output to the user:

INPUT "What is your name"; NAME$
PRINT "Hello, "; NAME$; "! ";
INPUT "How old are you"; age$
PRINT "The user, "; NAME$; " is "; age$; " years old"

Please note: The string will only store what the user enters, so you must make sure that when programming, you add spaces inside the quotation marks (as shown above) so that it reads properly. Not inserting spaces will concatenate the two words.

The input statement can be used with numerical variables, by automatically converting the string into the number. For example, you can prompt the age directly into an integer:

INPUT "Hello, "; NAME$; "! How old are you"; age

When using an integer with the input statement, any character that can't be understood as a number will print a "Redo from start" error message to the user, and retry the prompt.

Please note: The concatenation rules for a number differ from a string. While a string does not create spaces, a number will insert a space before and after itself when being printed.

Finally, the LINE INPUT command will read a line of text and place the result into a string. While this may seem to be the same command, the INPUT statement will parse commas as a delimiters between fields when multiple variables are passed to it.

[edit]

Basic Math

There are four numerical variables within QBasic:

Type Minimum Maximum
Integer -32,768 32,767
Long Integer -2,147,483,648 2,147,483,647
Float -3.37x10^38 3.37x10^38
Double -1.67x10^308 1.67x10^308

A lot of programming is math. Don't let this scare you: a lot of the math is simple, but it's still math. In this section, we will look at doing some basic math (the same stuff you learned in the 3rd grade) and manipulating numbers.

[edit] Equation Setup

In QBasic an equation has a basic setup a right side and a left side. For instance X=5, as you can probably figure out, this sets the variable X to 5. But we can use variables on the right side too. Y=X*10 would set Y equal to 10 times X, in this situation, 50. In this next program I will show several equations to give you a feel for math.

[edit] 07MATH.BAS

 CLS
 <br>
 'Set a-d to initial values
 a = 10
 b = 6
 c = 3.1415
 d = 3.333333
 <br>
 e = a + b
 PRINT a; "+"; b; "="; e
 <br>
 f = c * d
 PRINT c; "*"; d; "="; f
 <br>
 g = b - c
 PRINT b; "-"; c; "="; g
 <br>
 h = b / d
 PRINT b; "/"; d; "="; h
 <br>
 i = INT(d)
 PRINT "Remove the decimal from "; d; "="; i

[edit] Understanding 07MATH.BAS

The most important thing you can take away from this is the setup for math equations. I think you can figure out what all the symbols are and what they do, but QBasic is picky about equations. For 'e=a+b', if you try 'a+b=e' it will not work. The final thing I would like to address in 7MATH.BAS is the INT() function. As far as vocabulary, a function is something that takes in a piece of information and gives you another piece of information back. So PRINT, was a statement, and INT() is a function. The INT() function takes a number and truncates it's decimal, it does not round. So INT(5.1) is 5 and INT(5.999) is still 5. If you want to round a number use CINT().

[edit] 08MATH.BAS

 CLS
 INPUT "Enter a number: ", x
 PRINT
 <br>
 x = x + 5
 PRINT "X is now: "; x
 <br>
 x = x * x
 PRINT "X is now: "; x
 <br>
 x = x / 5
 PRINT "X is now: "; x
 <br>
 x = x - 4
 PRINT "X is now: "; x
 <br>
 x = x / x
 PRINT "X should be 1: "; x

[edit] Understanding 08MATH.BAS

08MATH.BAS shows one simple concept that is very important in programing, but impossible in math. The way that the computer calculates the equation is it does all the math on the right side of the equation and then sticks it in the variable on the left side. So the equation x=x+5 makes perfect sense, unlike math where it is a contradiction. Reassigning a value to a variable based on it's current value is common and a good way to keep the number of variables down.

[edit] 09TIP.BAS

 CLS
 INPUT "How much is your bill: ", bill
 INPUT "What percent tip do you want to give: ", tip
 <br>
 tip = tip / 100   'Change percent to decimal
 tip = tip * bill  'change decimal to money
 <br>
 PRINT
 PRINT "The tip is "; tip; "$."
 PRINT "Pay "; tip + bill; "$ total."

[edit] Tip Calculator

09TIP.BAS calculates you tip and total bill from the bill and percent tip you wish to give. The first three lines clear the screen and get the information from the user. The fifth line changes the tip from a percent to the correct decimal by dividing by 100 (ex. 20%=.2 because 20/100=.2) the next line takes that percent and turns it into a dollar value by multiplying the decimal value by the bill. So if your bill is $20.00 and you leave a 20% tip, it multiplies 20*.2 which is 4 or $4.00. The last three lines format the output.
This is a good example of a complete program. It collects information from the user, it processes the information and it gives the user feedback. Also, the middle section of the program is a good example of variable conservation. This is subject that will take some practice to get used to. In writing a program, if you use too many variables, it will become difficult to keep track of all of them. If you try and conserve too much, you code may become difficult to understand.

You may notice that the program may print more than two decimal places if you enter a bill that is not an exact dollar value. As an exercise, try modifying the program so that it only displays two decimal places - you can use the int function or any other rounding method you intend to use.

[edit] 10OROP.BAS

 'ORder of OPerations
 CLS
 a = 15
 b = 10
 c = 12.2
 d = 1.618
 <br>
 PRINT a * b + c   'these two are different
 PRINT a * (b + c)
 <br>
 PRINT
 <br>
 PRINT b - c / d   'these two are different
 PRINT (b - c) / d
 <br>
 PRINT
 <br>
 PRINT a * b - c * d / a + d   'these two are the same
 PRINT (a * b) - ((c * d) / a) + d

[edit] Parentheses and Order of Operations

10OROP.BAS is an example of order of operations and how parentheses can be used to manipulate it. I do not want to go into an indepth explanation of the order of operations here. The best advice I can give is unless you are sure of the order of operations, use parentheses to make sure the equation works how you want. All you need to know about parentheses is that the deepest nested parentheses calculate first. If you wish to know more, there are plenty of algebra resources available. On that note, you may wish to brush up on algebra. While it is not necessary for programming, it can help make programming easier and it can allow you to create more advanced programs.

[edit] Random Numbers

Though we will not go into their use until the next section, I would like to discuss the generation of random numbers. QBasic has a random number statement, RND, that generates a random decimal between 0 and 1. You can think of it as a random percent. At first, this may seem like an odd way to generate random numbers. However, with a little math it is very easy to manipulate this to provide numbers in whatever range you want.
The first step is to multiply RND by a number (the range you want). For instance 'RND*10'. This will return random numbers (decimal numbers) between 0 and 10(both included). So, to pick a random number between zero and ten we would say '(RND*10)'

[edit] 11RND.BAS

 CLS
 RANDOMIZE TIMER
 <br>
 PRINT "Random number from 0-9: "; RND * 10
 PRINT
 <br>
 PRINT "Random number from 1-10: "; (RND * 10) + 1
 PRINT
 <br>
 PRINT "Random integer from 1-10: "; INT(RND * 10) + 1
 PRINT
 <br>
 PRINT "Random even integer from 50-100: "; INT(RND * 25) * 2 + 50

[edit] More on RND

A few notes on 11RND.BAS, the second line, RANDOMIZE TIMER, sets it so that the computer uses the current time to pick random number. If you don't do this, it picks the same random number every time (try it, write a one line program, PRINT RND, and run it over and over, your screen will fill up with the same number) this can prove useful for some applications, but not most. Stick RANDOMIZE TIMER in at the top of all your programs that use the RND statement and they will be far less predictable. This program just show some ways to choose what you want from your random number generator. The last line shows that you can be very specific in what you get. Make sure to run this program several times to see the different results.

[edit]

Flow Control

[edit] Flow control

Flow control is the ability to redirect the execution point of a program based on conditions. In most cases, control relies on a specific condition being either true or false, but can also operate based on a loop counter or through some other means.

In QBasic, flow control may be written in one or two ways:

  • The flow control is contained within one line - usually the case with IF statements affecting one command
  • The flow control affects a block of code - which is the case if major portions of the program are affected by a loop or condition.

[edit] True or False

Boolean logic is the logic of things being true or false. In programing this logic is used to control what a program does. In order for the computer to decided if something is true or not, it must be stated in math terms. You cannot say 'Is it six o'clock', you have ask if 'time = 6.00'. The comparisons used in qbasic are equal (=), less than (<), greater than (>), less than or equal to (=<), greater than or equal to (>=) and not equal (<>). Also, to link together more than one comparison, there are logical operators. These are 'AND', 'OR' and 'NOT'. We will cover exactly what these mean later on, but you probably understand the first two already.

[edit] IF

One of the most useful statements in QBasic is the IF statement. It allows you to choose what your program will do depending on the conditions you give it. The next few programs will be taking a look at ways to use the IF statement.

[edit] 12IF.BAS

 CLS
 num = INT(RND * 100) + 1
 INPUT "Pick a number between 1 and 100: ", answer
 
 IF num = answer THEN PRINT "You win"
 IF num > answer THEN PRINT "Too Small"
 IF num < answer THEN PRINT "Too big"

[edit] Basic IF...THEN

12IF.BAS shows the most basic use of the IF...THEN statement. The format is

IF [conditional] THEN [do this]

In this program the conditionals check what the guess is relative to answer. One side note, this program does not have RANDOMIZE TIMER intentionally, this will allow you to play the game and keep getting closer to the number, the drawback is that once you find the number, the game has no replay value. We will make a better version a little later though.

[edit] 13IFELSE.BAS

 CLS
 num = INT(RND * 20) + 1
 INPUT "Pick a number between 1 and 20: ", answer
 
 IF answer = num THEN PRINT "You Win" ELSE PRINT "You Lose"

[edit] IF...THEN...ELSE

This version of the IF statement adds the the ELSE operator. The ELSE operator allows you to specify what happens if the conditional fails.

IF [conditional] THEN [do this 1] ELSE [do this 2]

So, if the conditional is true 'do this 1' will happen if the conditional is not true 'do this 2' will happen.

If needed, you can add ELSEIF to the IF...THEN statement. This allows a construct known as an IF...ELSE ladder, where the QBasic interpreter can select one code path based on a series of condition checks.

[edit] LOGIC

When forcing the computer to compare two variables with the IF statement, you must keep this in mind. "a" < "d" for A begins in the alphabet earlier than D. So, if you had, for example, a variable name D$="a" and a variable name A$="d" then the logical expression would end up coming out as... D$<A$ TRUE

[edit] 14FOR.BAS

 CLS
 num = INT(RND * 20) + 1
 FOR count = 1 TO 5
  INPUT "Pick a number between 1 and 20: ", answer
  IF answer = num THEN PRINT "You win after";count;"guesses!": END
 NEXT
 PRINT "You lose"

[edit] FOR...NEXT

The for loop allows you to create a counter - the variable may either be used within the loop, or in this case, provide a limit to the number of loops within a block of code. In the example above, the user is given five chances to guess the number, and if successful, is told how many attempts he made.

The syntax for the for statement is:

FOR <variable> = <start> TO <end> [STEP <increment>]

The incrementer may be positive or negative - if positive, it counts up, and if negative, it counts downward. The for loop stops when its value passes end after being incremented.

You can exit a for loop early with the EXIT FOR command.

[edit] 15WHILE.BAS

PRINT "Press any key to continue"
WHILE INKEY$=""
WEND

[edit] WHILE...WEND

The WHILE loop continues executing a block of code until the condition becomes false. In the example above, you see a press any key prompt that waits until the user presses a key. (The INKEY$ feature will be described under Advanced Input.)

[edit] DO...LOOP

The DO...LOOP construct is a more advanced of the WHILE loop - as with other flow control blocks, it is marked by DO and LOOP to denote the boundaries.

It relies on a conditional statement placed after either DO or LOOP:

DO
  a$ = INKEY$
LOOP WHILE a$=""

As an alternative, you can instead replace WHILE with UNTIL have the loop continue until a specific condition is met:

DO
  x=x+1
LOOP UNTIL x >= 10

[edit] SELECT CASE

The select statement is a substitute for repeated use of IF statements. It evaluates the test expression, and jumps to the appropriate control block. It supports strings and numbers, as well as multiple options within one case block.

INPUT "Enter your guess (1-10): ", guess
SELECT CASE guess
  CASE IS > 10
    PRINT "Your guess is out of range."
  CASE 1,2
    PRINT "Your guess is too low."
  CASE 3
    PRINT "Your guess is correct."
  CASE 4 TO 10
    PRINT "Your guess is too high."
END SELECT

If a parameter would be covered by more than one case statement, the first option will take priority.

[edit]

Advanced Input

[edit] INKEY$

Getting real time information from the user is a little more difficult. To do so, we will use the INKEY$ command, which checks to see if a user typed a key and provides the keypress to the program.

Look at this code and then we will look at it in depth:

 DO
   LET k$ = INKEY$
 LOOP UNTIL k$ <> ""
 SELECT CASE k$
   CASE "q"
     QuitProgram
   CASE "c"
     MakeCircle
   CASE "s"
     MakeSquare
 END SELECT

The first part is the DO-LOOP which constantly polls INKEY$ for a return value. In the basic use, INKEY$ returns an empty string if no keys are being pressed and continues with the program. Once a key is pressed, INKEY$ will return that key immediately.

[edit] The keyboard buffer

What is INKEY$ doing and how does it work?

While the INKEY$ command looks like it returns the key currently being pressed, this is not the case. It is used by the program to answer the question, "What is IN the KEYboard buffer?" To understand this you will need to understand what a basic buffer is and why it is used.

In older systems (not necessarily the IBM PC) a single chip processed keyboard input, and controlled the LED lights for caps lock and number lock. Because a computer does many things at once (e.g., take input from the mouse, crunch numbers, call subroutines, display new information on the screen), it needs to be able to remember what was pressed on the keyboard while it is busy. This chip contained some memory (called a buffer) that allow keeping track of a limited number of keypresses.

Within the Dos platform under IBM PCs, the hardware has changed slightly. Instead of a hardware buffer, pressing or releasing a key will interrupt the running program to add a keystroke to a software buffer located in the BIOS. This procedure is usually unnoticed by the user and has minimal impact on system performance. However, this buffer allows for 15 characters - attempting to overflow it when the computer is busy will cause a short beep and drop any further characters.

The INKEY$ command uses this buffer as a FIFO (First In First Out) buffer. As an example let's say you have a game that has a bouncing ball on the screen and a paddle at the bottom. The computer program constantly has to update the screen to show the movement of the ball. While it does this the program passes by an INKEY$ command to see what value is returned. If the user has pressed a key since the last time the command was invoked it will return that key. Let's say the ball is moving over to the right and the user needs to press the "R" key to tell the program to move the paddle right. Since the program is busy moving the ball and updating the screen, it does not instantaneously notice that the user has pressed the key. Instead, the key press is stored in the keyboard buffer, and retrieved a few milliseconds (or microseconds) later when the INKEY$ command is used.

In many programs (as above), INKEY$ will appear nested in a loop. It is requested over and over again. This allows the program to get user input one character at a time. Using our example above, the user may need to press R over and over again until the paddle is under the ball. On the other hand, the user may press R too many times and need to press L to move it left. Because the INKEY$ command is using a FIFO buffer it will always retrieve the keys pressed in the same order as they where typed.

In summary, the INKEY$ command will always return and remove the first character in the keyboard buffer. Generally speaking, it is used over and over to retrieve every key that has been pressed, and to allow a user to interact with a program in a close approximation to "real time." If there is no key in the keyboard buffer, INKEY$ it will return an empty string (no character).

[edit] Scancodes

Some keypresses are not associated with an ASCII character. When one of these keys is pressed, INKEY$ returns a string with two characters = the first character is a null (ASCII code 0), and the second is the raw scan code for the keyboard. A full listing of the scancodes can be found within the QBASIC help file - you can also determine the scan codes by examining the results of INKEY$ as you press those keys in question.

NOTE:
Some keys cannot be directly detected by INKEY$.

[edit]

Subroutines and Functions

[edit] Purpose

Subroutines and functions are ways to break up your code into a reusable form. They allow the programmer to do a large set of operations just by calling the appropriate procedure or function. For example, lets say you need to PRINT a lot of lines, such as instructions. One way to do this is to just enter all your PRINT commands directly into where you need them. At some point, you may want to move the PRINT commands, or you may use the exact set of PRINTs elsewhere in the program. To move or change all of the PRINT commands would be quite a hassle. A simpler way would be to create a procedure and enter all of the PRINT commands there; then, when you need to execute the commands, you may simply call your procedure and it will execute each line in its body.

[edit] Procedure vs. Function

A procedure DOES something and does not return anything for the programmer. For example, a procedure might be used to set the screen mode and palette.

A function does something and RETURNS a value. For example, if you need to find the average of two values, you might write a function that takes in two numbers and returns the average.

[edit] GOTO and GOSUB

The GOTO and GOSUB statements were the original methods at which functions were created. They were the most common on older basic implementations and are kept around for compatibility reasons; however, their use is not recommended in other programming languages or in large scale projects.

These two commands depend on labels, which come in one of two forms. The first and older form involves writing line numbers at the beginning of each line (usually in increments of 10). The newer method looks similar to other programming languages, which is a single word followed by a colon.

The GOTO statement is simple; it moves the execution point to a given label:

 

The GOSUB statement transfers control to a given label, and is paired with a corresponding RETURN statement.

 

[edit] ON ERROR

The ON ERROR allows you to define an error handler for your program; when an error occurs, it immediately jumps to the given label. The control returns once the program reaches a RESUME statement, which can either return control to the same point, the next statement, or any other desired label.

Within Qbasic, the error handler cannot be located within any subroutines. As such, any error checking or flags will have to be handled through the use of variables that are shared with the main module.

NOTE:
While the QBasic documentation states ON ERROR RESUME NEXT is a valid statement, this is incorrect.

NOTE: If your error hanedling routine does not have a "resume" statement in it (IOW you try to do it all with gotos) error handeling will only work once - the next "on error" will be ignored and the program ends as if you had no "on error" statement at all. This problem does not seem to be mentioned in any of the documentation. It took me three hours to figure out why two nearly identical program portions acted so differently.

[edit] Declaring a subroutine

A superior method of declaring a subroutine is using the SUB statement block. Under the QBasic IDE, doing so moves the SUB block to it's own section in the window to prevent accidental deletion of the module, and allows the easier organization of the program code.

Calling a function is as simple as writing the name of the function (passing any required parameters.) If you want, you can use the CALL statement to indicate to other programmers that it is a subroutine.

SUB NAME (params) 
  ' Shared variable declarations
  ' ...
END SUB

Parameters passed into subroutines are passed by reference - if they are changed, their value is also changed in the calling function as well.

All variables used within the subroutine are transient by default. If you want the values to persist across calls, you can put the static keyword at the end.

If you need access to a global scoped variable, they need to be declared using the SHARED keyword. To so do, Put the SHARED statement at the beginning of the subroutine, and list the variables you need access to.

[edit] Declaring a function

A function is a form of subroutine that returns a value. Everything that applies in defining a subroutine also applies to a function. Within the function, the return value is created by using the function name as a variable - the return value is then passed to the calling expression.

FUNCTION NAME (params) 
  ' Shared variable declarations
  NAME = result
  ' ...
END FUNCTION

Functions are declared in the same way as variables - it returns the variable type it's defined to return, in the same way variables are defined to contain their specified type. By default, it is a number, but appending a dollar sign indicates that it is returning a string.

Functions can only be called within an expression; unlike subroutines, they are not a standalone statement.

[edit]

Arrays and Types

[edit] Built-in Types

QBasic has five built-in types: INTEGER (%), LONG(&), SINGLE(!), DOUBLE(#) or STRING($). You can declare a variable to one of these types by adding the type character after the variable name.

An alternate method of declaration is using the DIM statement:

 DIM NAME AS STRING

[edit] User-defined types

TODO

TODO
Make this example more suitable for textbook usage.

A user defined type allows you to create your own data structures.

 TYPE asdf
  zxcv AS INTEGER
 END TYPE

You can then declare variables under this type, and access them:

 DIM qwer AS asdf
 qwer.zxcv = 1

[edit] Arrays

An array is a collection of values stored in a single variable. While you can use arrays directly without first declaring them, they are limited to 10 elements on each dimension.

By default, arrays in QBasic are static in size and cannot be changed later in the program. Code that will set up this type of array is as follows:

DIM myArray(10) AS TYPE

TYPE can be any of the built in QBasic or user-defined type. If this is not specified, the array takes the default type for the variable.

By issuing the Meta Command '$DYNAMIC at the beginning of your program you can cause your arrays to be dynamic:

 ' $DYNAMIC
 DIM myDynamicArray(5) AS INTEGER
 REDIM myDynamicArray(10) AS INTEGER

This is now perfectly legal code.

To free up space occupied by an array, use the ERASE statement.

[edit] Multidimensional arrays

An array isn't restricted to one dimension - it's possible to declare an array to accept two parameters in order to represent a grid of values.

 DIM housenames(25,25) AS STRING

You cannot use the REDIM statement to change the number of dimensions on the array, even with dynamic allocation.

[edit] Non-zero base

In most languages, arrays start at the value 0, and count up. In basic, it's possible to index arrays so that they start at any value, and finish at any other value.

 DIM deltas(-5 TO 5)

You can change the default lower bound with the OPTION BASE statement.

[edit]

Appendix

[edit] Commands

[edit] ABS()

PRINT ABS(54.345) 'This will print the value exactly as it is (54.345)
PRINT ABS(-43)    'This will print the value as (43)

This returns an absolute value of an expression within the brackets, turning a negative to a positive (e.g. -4 to 4)

[edit] ACCESS

OPEN "file.txt" FOR APPEND ACCESS WRITE

This sets the access of a file that has been declared into the program. There are three settings that the programmer can set. These are:

READ - Sets up the file to be read only, no writing.
WRITE - Writes only to the file. Cannot be read.
READ WRITE - Sets the file to both of the settings above.

[edit] ASC()

PRINT ASC("t")  'Will print 116

This returns the ASCII number of the character within the brackets. If the programmer put in a string into brackets, only the first character of the string will be shown.

[edit] ATN()

ATN( 23 / 34 )

Part of the inbuilt trigonometry functions. This the Arc-Tangent, it converts the values to an angle.

[edit] BEEP

BEEP

Allows a "Beep" sound emit from the PC speaker.

[edit] CASE

SELECT CASE [variable]
CASE [value]: [command]
CASE ELSE: [command]
END SELECT

Use this when using multiple values in your program and assigning them separate paths. This is an example of a program with no CASE commands that assigns different paths to values:

10 PRINT "1. Print 'path'"
PRINT "2. Print 'hello"
PRINT "3. Quit"
INPUT "Enter a choice: "; a$
IF a$ = "1" THEN
PRINT "path"
GOTO 10
IF a$ = "2" THEN
PRINT "hello"
GOTO 10
IF a$ = "3" THEN END
PRINT "That is not a valid choice"
GOTO 10

This is what a program looks like with the CASE command:

PRINT "1. Print 'path'"
PRINT "2. Print 'Hello'"
PRINT "3. Quit"
INPUT "Enter a choice: "; a$
SELECT CASE a$
CASE "1":
PRINT "path"
CASE "2":
PRINT "Hello"
CASE "3":
END
CASE ELSE:
PRINT "That is not a valid choice"
END SELECT

[edit] CHAIN

CHAIN [filename].[format]

This lets the program transfer variable values from one program to another. You can either open a QBasic file (.bas) or a compiled file (.exe). The COMMON statement has to be declared before any CHAIN command can be run in the program.

[edit] CHDIR

CHDIR [directory name]

This is used for changing a directory. Used in conjunction with MKDIR and RMDIR. The directory name is declared exactly like in DOS PROMPT. For example:

CHDIR "c:/Program Files/QBasic_FIles/Testing_Files"

To use this command, the programmer will have to know how MS DOS and COMMAND PROMPT work.

[edit] CHR$()

This returns the string value of an ASCII character.

CHR$([Character number])

This is used a lot for inputting keyboard keys. Some keyboard keys cannot be type (e.g. the Esc key or the F Buttons). So the programmer has to make up for this with the CHR$ command. Here is a list of some character numbers:

08: Backspace
09: Tab
27: Esc
72: Up Arrow
75: Left Arrow
77: Right Arrow
80: Down Arrow

The numbers are based on the ANSI codes. There are 225 different characters to choose from.

[edit] CINT()

This rounds the integer within the brackets to the nearest integer.

PRINT CINT(4573.73994596)

[edit] CIRCLE

CIRCLE ([X Coordinate], [Y Coordinate]), [Radius], [Colour]

Lets the programmer display a circle. Like all graphics commands, it must be used with the SCREEN command.

[edit] CLEAR

CLEAR

Resets all variables, strings, arrays and closes all files. The reset command on QBasic.

[edit] CLOSE

CLOSE #[number of file]

Closes a file that has been opened in a QBasic program.

[edit] CLS

CLS

Clears the active screen. Erases all text, graphics, resets the cursor to the upper left (1,1), and also applies the current background color (this has to be set using the COLOR command) to the whole screen.

[edit] COLOR

COLOR [Number of Colour]

This lets you change the colour of the text in the program. It can be done like this:

COLOR 14
PRINT "Yellow"

You have a choice of sixteen colours:

00: Black            08: Dark Grey
01: Dark Blue        09: Light Blue
02: Dark Green       10: Light Green
03: Dark Cyan        11: Light Cyan
04: Dark Red         12: Light Red
05: Dark Purple      13: Magenta
06: Orange Brown     14: Yellow
07: Grey             15: White

These values are the numbers that you put in the COLOR command.

[edit] COMMON

Declares variables as global.

COMMON SHARED [variablename]

The COMMON statement must be declared before any statements that are executable in the program. This is an example of a non-executable statement.

[edit] CONST

This declares a value as a constant. Which means that the value cannot be changed within the program.

CONST Name AS INTEGER
CONST Name AS STRING

These are put at the beginning of a program.

[edit] DATA

DATA [constant]

Use in conjunction with the READ and RESTORE command. Mostly used in programs dealing with graphics, this command lets QBasic read a large number of constants. The READ command accesses the data while the RESTORE command "refreshes" the data, allowing it to be used again.

[edit] DATE$

This declares the date of the system. It is in the format of mm-dd-yyyy. Use it like this:

a$ = DATE$

[edit] DIM

This this is used to declare variables, either singular or an array of variables.

DIM [Array Name]$ ([Number Of values])

This is used for building arrays. Input the values using the LET command, like this:

DIM Name$ (3)
LET Name$ (1) = "John"
LET Name$ (2) = "Mary"
LET Name$ (3) = "Peter"

For inputting single variables, the programmer inputs the data like this:

DIM Name AS STRING   'Declaring a string variable
DIM Name AS INTEGER  'Declaring an integer variable
DIM Name AS DOUBLE   'Declaring a variable as both a string and an integer

These values can be changed within the program.

[edit] DO

DO
[program]
LOOP UNTIL [condition]

Used to create a loop in the program. This command checks the condition after the loop has started. This is used with the LOOP command. This is a very simple example:

num$ = 1
sum$ = 0
DO
sum$ = 2 * num$
PRINT sum$
num$ = num$ + 1
LOOP UNTIL num$ = 13

This program outputs the Two Times Tables up to 12. The Reason why we put 13 is that the program stops at that point and does not continue the loop. If we put LOOP UNTIL num$ = 12 the last output on the screen would be "22".

[edit] DRAW

DRAW [string expression]

This is used to draw lines. This will draw a line at the last pixel coordinate and colour stated in the program. It draws according to the directions, angles, and lengths stated in the string expression. Here is how to use the command:

SCREEN 7
PSET (50, 50), 4
DRAW "u50 r50 d50 l50"

This program will draw a red square at the coordinates of the pixel started. It will also colour it to the colour number. It is really a free movement shape command, unlike the LINE or CIRCLE command were you can only draw one style of object. You notice the letters at the front of each number, that is the direction the line should go. Here is the chart:

U = Up    E = Upper-right
D = Down  F = Lower-right
L = Left  G = Lower-left
R = Right H = Upper-left

The number that follows the letter is the length of the line in pixels.

[edit] END

END

Signifies the end of the program. When QBasic sees this command it usually comes up with a statement saying: "Press Any Key to Continue".

[edit] END IF

END IF

Ends the program if a condition is reached.

[edit] ENVIRON

ENVIRON [string expression]

NOTE: If you are running QBasic on a Windows system, you wont be able to use this command.

This command lets you set an environment variable.

[edit] EOF()

This checks the file that is being read if there is still data to be read.

OPEN File.txt FOR INPUT AS #1
DO
INPUT #1, text$
PRINT text$
LOOP UNTIL EOF(1)
END

The integer in the EOF brackets is a boolean / binary value, a one or zero. 0 if the line of the file still contains data and a 1 if the line of data stops.

[edit] ERASE

ERASE [arrayname] [,]

Used to erase all dimensioned arrays.

[edit] ERROR

ON ERROR GOTO [stated line label]
ERROR [error number]

ON ERROR GOTO is used to go around error events when the occur. ERROR manually causes a fake error, used mainly for troubleshooting the error trapping code. The error number chart is as follows:

1 NEXT without FOR                 39 CASE ELSE expected 
2 Syntax Error                     40 Variable required 
3 RETURN without GOSUB             50 FIELD overflow 
4 Out of DATA                      51 Internal error 
5 Illegal function call            52 Bad file name or number 
6 Overflow                         53 File not found 
7 Out of memory                    54 Bad file mode 
8 Label not defined                55 File already open 
9 Subscript out of range           56 FIELD statement active 
10 Duplicate definition            57 Device I/O error 
11 Division by zero                58 File already exists 
12 Illegal in direct mode          59 Bad record length 
13 Type mismatch                   61 Disk full 
14 Out of string space             62 Input past end of file 
16 String formula too complex      63 Bad record number 
17 Cannot continue                 64 Bad file name 
18 Function not defined            67 Too many files 
19 No RESUME                       68 Device unavailable 
20 RESUME without error            69 Communication-buffer overflow 
24 Device timeout                  70 Permission denied 
25 Device Fault                    71 Disk not ready 
26 FOR without NEXT                72 Disk-media error 
27 Out of paper                    73 Advanced feature unavailable 
29 WHILE without WEND              74 Rename across disks 
30 WEND without WHILE              75 Path/File access error 
33 Duplicate label                 76 Path not found 
35 Subprogram not defined 
37 Argument-count mismatch 
38 Array not defined 

[edit] FOR

FOR [variable] = [Value]

This is used when mostly dealing with the LOOP and NEXT command. Usually used to input a large amount of numbers. For example:

FOR a = 200 TO 300
PRINT a
NEXT a

This program would print out all numbers in between 200 and 300.

[edit] GOSUB

GOSUB [subroutine]

This lets you go into a subroutine in a program. It is used with the RETURN command when writing subroutines.

[edit] IF

IF [variable or string] [operator] [variable or string] THEN [command]

Compares variables or strings. For example, if you wanted to examine whether or not a user-entered password was the correct password, you might enter:
IF a$ = "password" THEN PRINT "Password Correct"
Where a$ is the user entered password. Some operators include:
"="- equal to
"<"- less than (only used when variable or string is a number value)
">"- greater than (only used when variable or string is a number value)
"<>"- does not equal
"<="- less than or equal to (only used when variable or string is a number value)
">="- greater than or equal to (only used when variable or string is a number value)
One can also preform actions to number values then compare them to other strings or variables using the if command, such as in the below examples:
IF a+5 = 15 THEN PRINT "Correct"
IF a*6 = b*8 THEN PRINT "Correct"

[edit] INKEY$

[variable] = INKEY$

This is used when you want a program to function with key input from the keyboard. Look at this example on how this works:

a$ = INKEY$
PRINT "Press Esc to Exit"
END IF a$ = CHR$(27)

You can use this in conjunction with the CHR$ command or type the letter (e.g. A).

[edit] INPUT

INPUT [String Literal] [,or;] [Variable]

Displays the String Literal, if a semi colon follows the string literal, a question mark is displayed, and the users input until they hit return is entered into the variable. The variable can be a string or numeric. If a user attempts to enter a string for a numeric variable, the program will ask for the input again. The String Literal is option. If the string literal is used, a comma (,) or semicolon (;) is necessary.

[edit] LET

LET [variable] = [value]

Lets the program know what a variable is valued at.

[edit] LINE

LINE ([X], [Y]) - ([X], [Y]), [Colour Number]

Used for drawing lines in QBasic. The first X and Y are used as coordinates for the beginning of the line and the second set are used for coordinating were the end of the line is. You must put a SCREEN command at the beginning of the program to make it work.

[edit] LOOP

DO
[Program]
LOOP UNTIL [condition]

Used to create a loop in the program. This command checks the condition after the loop has started. This is used in conjunction with the DO command.

[edit] LPRINT

LPRINT [statement or variable]

Prints out text to a printer.

[edit] OPEN

OPEN "[file name and format]"

This opens a file. You have to write the full name, for example:

OPEN "file.txt"

See that the file name and format of file is written.

[edit] READ

READ [Variable]

Used in conjunction with the DATA command, this command lets QBasic read data. This is mostly used when dealing with large quantities of data like bitmaps.

[edit] REM

REM [Comment]

This is a command that lets anything within the line Written after the REM command not be read by the computer. It is used only to write comments and any notes for aiding the programmer or programmers using the program.

[edit] RETURN

RETURN

Signifies that it is the end of a subroutines

[edit] PLAY

PLAY "[string expression]"

Used to play notes and a score in QBasic. The tones are indicated by letters A through G. Accidentals are indicated with a "+" or "#" (for sharp) or "-" (for flat) after the note letter. See this example:

PLAY "c c# c c#"

There are also codes that sert the duration, octave and tempo. PLAY executes the commands or notes the order in which they appear in the string. Any indicators that change the properties are effective for the notes following that indicator.

Ln     Sets the duration (length) of the notes. The variable n does not indicate an actual
duration amount but rather a note type; L1 - whole note, L2 - half note, L4 - quarter note, etc. (L8, L16, L32, L64). By default n = 4. On Sets the current octave. Valid values for n are 0 through 6. An octave begins with C and
ends with B. Remember that C- is equivalent to B. MN ML MS Stand for Music Normal, Music Legato, and Music Staccato. MN - Note duration is 7/8ths of the length indicated by Ln. ML - Note duration is full length of that indicated by Ln. MS - Note duration is 3/4ths of the length indicated by Ln. Pn Causes a silence (pause) for the length of note indicated (same as Ln). Tn Sets the number of "L4"s in a minute. Valid values are from 32 to 255. The default value is T120. . (period) When placed after a note, it causes the duration of the note to be 3/2 of the set duration. This is how to get "dotted" notes. "L4 C#." would play C sharp as a dotted quarter note. MB MF Stand for Music Background and Music Foreground. MB places a maximum of 32 notes in the music buffer and plays them while executing other statements. Works very well for games. MF switches the PLAY mode back to normal. Default is MF.

[edit] PRINT

PRINT [Argument] [,or;] [Argument]...

Displays text to the screen. The Argument can be a string literal, a string variable, a numeric literal or a numeric variable. All arguments are optional.

[edit] PSET

PSET ([X coordinate],[Y coordinate]), [Pixel Colour]

This command displays pixels, either one at a time or a group of them at once. For the command to work, the program must have a SCREEN command in it.

[edit] SCREEN

SCREEN [Screen Mode Number]

This command is used for displaying graphics on the screen. There are ten main types of screen modes that can be used in QBasic depending on the resolution that you want. Here is a list of what screen modes you can choose from:

SCREEN 0: Textmode, cannot be used for graphics. This the screen mode that text based programs run on.

SCREEN 1: 320 x 200 Resolution. Four Colours

SCREEN 2: 640 x 200 Resolution. Two Colours (Black and White)

SCREEN 7: 320 x 200 Resolution. Sixteen Colours

SCREEN 8: 640 x 200 Resolution. Sixteen Colours

SCREEN 9: 640 x 350 Resolution. Sixteen Colours

SCREEN 10: 640 x 350 Resolution. Two Colours (Black and White)

SCREEN 11: 640 x 480 Resolution. Two Colours

SCREEN 12: 640 x 480 Resolution. Sixteen Colours

SCREEN 13: 320 x 200 Resolution. 256 Colours. (Recommended)

[edit] SOUND

SOUND [frequency], [duration]

Unlike the BEEP command, this produces a sound from the PC speakers that is of a varible frequency and duration. The frequency is measured in Hertz and has a range from 37 to 32767. Put in one of these numbers in the frequency section. The duration is clock ticks that is defaulted at 18.2 ticks per second.

[edit] THEN

[Command] [variable] = [value] THEN GOTO [line command value]

Used in conjunction with the GOTO or IF condition commands. It tells the computer what to do if a certain condition has been met.

[edit] TO

[Command] [Variable] = [Value] TO [Value]

Usually used to input a number of variables.

FOR a = 400 TO 500
PRINT a
NEXT a

This example will print all numbers from 400 to 500. Instead of declaring all values separately, we can get them all declared in one go.

[edit] Val()

Val([variable])

This turns a string into its numerical value.

[edit] Source Code

[edit]

Authors

< Programming:QBasic

Faraaz Damji (Frazzydee)
Adam Colton
Gareth Richardson (Grich)
Not a book title page. Please remove {{alphabetical}} from this page.