Qbasic Tutorial For Beginners and Newbies
Qbasic Tutorial For Beginners and Newbies
Qbasic Tutorial For Beginners and Newbies
QB-TUTORIAL
BY NEO DEUS EX MACHINA
HTTP://WWW.BLINDCODING.CJB.NET
THIS TUTORIAL
In this tutorial, specific ways of text-decoration are used to keep things clear. I will explain
them now.
This is normal text decoration ;-)
This is a remark
This is code-decoration
This is an exclamation
A note
I think that was everything. Although still a note: not all examples in this tutorial are tested.
So there might be some bugs in them.
DATA TYPES
There are 6 data types available in QB, which should be more than enough. . They are all
explained here. Well, here they come:
Integer is the first and most important data type. This data type is the most used data type of
all. You can store only non-decimal numbers in an integer. Since an integer contains 16 bits, you
can only store values from 32768 up to 32767.
Long integer is the second. Long integers are not used that often, since mostly integers
work fine. Long integers are actually the same as normal integers, so only non-decimal numbers.
However, a long integer contains 32 bits, allowing you to store values from 2147483648 to
2147483647.
Single, which can contain decimal numbers. Singles are 32 bit and you can store values
from around 9e40 to 9e-39.
Double, which can also contain decimal numbers. The only difference is that doubles are 64
bits large, thus providing space for values from around 9e305 to 9e-310.
String. The string is a special type. It can contain characters like A or . Strings are
always notated with double quotation marks around them. (). The length of the character-list can
range up to 64k.
String * n%, which is a string with a set length. Viz.: n characters can fit in the string.
That were them all. Each data type also has its own postfix-sign. I.e. that if you call a
variable for instance number%, the variable is called number and declared as an integer. If
variables dont have a post-fix sign, they are singles, unless you said them not to be ;-). Here are all
postfixes:
Integer: %
Long: &
Single: !
Double: #
String: $
REMARKS IN CODE
You can also put remarks in your code, which can make your code more clear to yourself
and other people reading your program. To make a remark in code, use a single quotation mark ()
followed by the remark. You can also use the command called Rem which actually does nothing
so its suitable for remarking (Rem is an abbreviation of remark).
Print shows something on the screen. The command itself accepts everything
from strings to numerical values.
Stops your program (and returns to the QB-IDE if running from the IDE).
You dont have to write the commands all in capital, the IDE does this automatically for
you.
You can always use the keycombination [Ctrl]+[Break] to immediately stop the program.
7
This is grey text!
4
This is red text! :)
15
White text!
0
You cant see black text though! :)
Run the program. If you already knew what Print did, youll probably now know what Color
does.
COLOR
fground% Sets the current foreground color to fground% and the background color
[, bground%]
to bground% (bground% is optional, thus you dont have to specify one).
(Note the integer-postfix, so number must be an integer). For now, we
only use 16 colors:
0 = Black
1 = Blue
2 = Green
3 = Cyan
4 = Red
5 = Magenta
6 = Brown
7 = Gray
8 = Dark gray
9 = Light blue
10 = Light green
11 = Light cyan
12 = Light red
13 = Light magenta
14 = Yellow
15 = White
You should know these values and colors by heart!
This isnt the end. Youll now watch how you can position some text on the screen:
4
CLS
LOCATE 1, 1
PRINT Upper left
LOCATE 1, 69
PRINT Upper right
LOCATE 13, 30
PRINT Somewhere in the middle
LOCATE 25, 69
PRINT Lower right;
END
Using locate, we can though position text on the screen. With positioning, it might be handy
to know what the numbers behind Locate mean. Well, the first is the y-coordinate, the second is the
x-coordinate. The y-coordinates range from 1 to 25 (1 is the first line, 25 the last). The xcoordinates range from 1 to 80 (1 is the most left and 80 the most right).
CLS
LOCATE y-cord%, x-cord%
Of course, Locate can also be used in conjunction with Color to create colored and
positioned text. Note that Locate only applies to the next Print-command encountered, Color
applies to all Print-commands until another color is set using another Color-command.
Did you notice the ; behind the last print command? I hope so A ; has been put at the
end of the print command because the last two lines of the screen (y-cords 24 and 25) are a little
weird. Normally, when you put text there, the entire screen shifts 1 line up, thus removing
everything on the first line. The ; at the end of a print command, prevents the screen from shifting
up.
If you specify a number behind sleep, the Sleep command waits that many
seconds before proceeding. If you dont specify a number, Sleep waits
until a keypress before proceeding.
Pressing a Control-key during a Sleep-command (with a value specified), will cause the
Sleep command to be skipped. So if you say Sleep 1000 and someone presses the Control-key, the
computer immediately proceeds with the next command.
First, it shows the text stored in text$, then asks the user to
enter a value for variable. If you use a comma or a semicolon
as separation-mark youll get a question mark or no question
mark at the end. (A comma gives none, a semicolon gives one
at the end of the text).
Note: you dont have to put double quotation marks when entering a string value. If your
program asks you to.
CHAPTER PROGRAM
You probably dont know yet, but at the end of each chapter, there is an example program
and some exercises about everything you know so far. You at least should have made all exercises
before proceeding to the next chapter.
CLS
DIM favoritecolor AS INTEGER
LOCATE 10, 10
PRINT Please enter your favorite color-number beneath:
LOCATE 11, 10
INPUT Yes here:, favoritecolor
COLOR favoritecolor
PRINT So your favorite colornumber is:; favoritecolor
PRINT Now press a key to proceed
SLEEP
PRINT Quitting this program Please wait 5 seconds
SLEEP 5
END
Now for the exercises
Exercise #1: Show all colors on screen by showing the text this is text with on the s the
colors name.
Exercise #2: Same as Exercise #1 but now show it exactly at the most right of the screen.
Exercise #3: Ask the user for his ASL then show the statistics in an emptied screen.
Exercise #4: Make a kind of interview with the user with about 10 questions. At the end, show a
report about the users answers. (E.g. if the user said his name is Harold in the report it must say
His name is Harold).
LTRIM$(astring$)
RTRIM$(astring$)
SPACE$(number%)
STR$(number%)
VAL(astring$)
ASC(char$)
CHR$(asciicode%)
I understand if you cant understand it all at once, but that is no problem. The only thing you
havent had yet are Functions, Statements, Expressions and Metacommands. Ill explain them here
(except the metacommands).
If a command is a statement, that command is a master-type. What do I mean with that?
Well, for example PRINT is a statement. Statements are commands which do something, but do not
return anything. They just do something. Like PRINT, it prints something on the screen, and it
doesnt do more.
Well, the thing is, that there are Functions too. Functions always return a value or a string
and can never stand-alone. Just try to type CHR$(139) in the IDE and try to run. Youll get an error!
Why? Simply because CHR$ returns a value, but the QB IDE cant do anything with it, does the
IDE has to show it on the screen? Or does it have to put it in a variable? Thats why functions never
are standalone, you always have to specify what the QB IDE has to do with the return value. You
can say: PRINT CHR$(139) or MyString$ = CHR$(139). Because now the IDE knows what it has
to do with it. In the first case, it prints the returns value of Chr$(139) to the screen, in the latter, it
stores the return value of Chr$(139) in MyString$.
QB also knows things that are called expressions. Expressions are some kind of formulas
like 3 + 1. You have often used expressions already, although you probably didnt know that.
Expressions can also contain functions like this one: 3 + SQR(5). The SQR function simply
calculates the Square Root of, in this case, 5. Just like functions, expressions are not standalone.
This is very easy to explain. For instance, if you type 3 + 3 in the IDE then try to run it, youll get
errors, why? Because when the compiler sees the line 3+3 you just typed, it thinks hrrmmm 3+3
and then? 3+3 so what? What do I have to do with 3+3? You can for instance specify that the
answer of 3+3 must be printed to the screen, or that it must be stored in a variable. By doing this:
PRINT 3 + 3
Answer% = 3 + 3
Also, functions and expression can be nested, the statements cannot. Simply look at the
following example, it looks kinda complex, but it is actually the ABC-formula (Maths!!
Remember?).
PRINT This is the ABC-Formula Calculator
PRINT You must enter values with the corresponding
PRINT formula: y = a * x ^ 2 + b * x + c
INPUT Please enter a:, a!
INPUT Please enter b:, b!
INPUT Please enter c:, c!
PRINT
D# = b! ^ 2 4 * a! * c!
PRINT Discriminant =; D#
X1 = (-b! SQR(D#)) / (2 * a!)
X2 = (-b! + SQR(D#)) / (2 * a!)
PRINT First zero-point at x =; X1
PRINT Second zero-point at x =; X2
END
I hope you understand it ;-).
9
10
STRUCTURE I: CHOICES
QB is also able to make choices, by a special command called IF. You must specify an
expression (which must return a boolean) behind the IF, then a THEN then type what is going to
happen if your expression is true. Perhaps itll be more clear if I show you an example:
PRINT Please enter a number
INPUT Number:, number%
IF number% = 0 THEN PRINT You entered a zero
IF number% <> 0 THEN PRINT You didnt enter a zero
When you read this program, it should have been cleared up by now, because you now know
that the first If checks if number% = 0 and if so, it prints you entered a zero on the screen. The
second checks for number% 0 and if so, it prints you didnt enter a zero on the screen.
In QB, the character doesnt exist. Instead of that, you should use <> for not equal to.
Actually, the first example was inefficient, because 2 if commands were needed. I could
extend your knowledge now by showing you this example:
PRINT Please enter a number
INPUT Number:, number%
IF number% = 0 THEN PRINT ZERO! ELSE PRINT No Zero! :(
Youll probably already understand what this program does, but lets explain anyhow. The If
command now checks if number% is equal to 0, if so, it prints zero! on the screen, if not it prints
no zero! on the screen.
This If-structure can be more extended by starting a second line. This is very handy, because
then you can execute more commands when an expression is true. Watch this:
PRINT Please enter a number
INPUT Number:, number%
IF number% = 0 THEN
PRINT Division by zero isnt allowed.
PRINT Please try again
END
ELSE
PRINT This entry will not cause an error
PRINT Because there is no division by zero
PRINT The answer is:; 1 / number%
END IF
I think this example should be clear enough. For the ones who dont understand, this
program will calculate 1/number% for a number entered by the user. If the user enters a 0, the part
between the If and the Else will be executed. If it isnt a 0, the part between the Else and the End If
is exectuted.
Note: if you put the whole IF statement on one line, which is possible, you dont have to use
an End If. This is only used for If statements which are not written on one line. The End If simply
defines where the piece of code, which belongs to an If-statement, ends.
Theres actually 1 function of If left, which is Elseif. Try to understand this example:
10
11
12
END SELECT
Defines a label with name label. You can fill your own name in for label, like
done in the example.
Jumps to the label called label. From there, the program will continue.
If you refer to a label (using Goto) that doesnt exist, youll get an error.
In some cases, Goto can be handy. However, overuse of the command will result in what is
called spaghetti-code. The code will then be that complex, that even the best programmer cant
12
13
understand the code, which is due to the fact that when using Goto, the code can be run on
numerous ways. So use Goto with caution.
Thats why they invented Gosub. Which will, in some cases, work more efficient than
Goto. By declaring a module-level sub, this works almost the same as a procedure or function (Sub
or Function). The only difference between Gosub and Goto is that Gosub requires a Return
statement. As youd already seen in the example above, Goto doesnt require any. Well, lets just
show you an example:
CLS
PRINT I can calculate contents
PRINT Please enter which contents you want to calculate
PRINT (cube, cylinder, ball)
Again:
INPUT Type it here:, choice$
Choice$ = LCASE$(LTRIM$(RTRIM$(choice$)))
Cont% = 0
SELECT CASE choice$
CASE cube
INPUT Please enter l:, l%
CASE cylinder
INPUT Please enter r:, r%
INPUT Please enter h:, h%
CASE ball
INPUT Please enter r:, r%
CASE ELSE
GOTO Again
END SELECT
IF choice$ = cube THEN
GOSUB calccubecont
ELSEIF choice$ = cylinder THEN
GOSUB calccylindercont
ELSEIF choice$ = ball THEN
GOSUB calcballcont
END IF
PRINT Contents:; Cont%
END
Calccubecont:
Cont% = l% ^ 3
RETURN
Calccylindercont:
Cont% = 3.1415! * (r% ^ 2) * h%
RETURN
Calcballcont:
Cont% = (4 / 3) * 3.1415! * (r% ^ 3)
RETURN
I think it is clear by now, but lets explain anyhow. The Gosub command on line 21, refers to
a label called calccubecont. In the previous section about Goto, Ive already explained what a
label can do. The program then jumps to that label, running everything what is said below. Until the
13
14
program arrives at a Return. Which is used to show the program the piece of code to be run is over
and the program jumps back to the Gosub command it came from, but now ignoring it and thus,
proceeding with the code after the Gosub command.
GOSUB label
RETURN
Works almost the same as Goto. Have the program jump to the specified
label.
Gosub requires this command, specifying the end of the label-code.
When reaching this command, the program jumps back to the last Gosub
command it came from.
When either overusing the Gosub command, or nesting them, this will result in a memory
error. So try to avoid it.
Nesting is consequently putting commands of the same purpose in eachother. This is e.g.
possible with If-statements (putting an If inside an If, which also is inside an If). It can also be done
with Gosub or Select. Later on, youll learn that it is also possible with Do, For and While.
CHAPTER PROGRAM
Ready? I hope so.
Again:
CLS
COLOR 15, 1
PRINT ==================================
PRINT
===========
===========
PRINT
=== Palindromotron ===
PRINT
===========
===========
PRINT ==================================
COLOR 7, 0
PRINT This program is capable of reversing
PRINT words, sentences or entire texts.
DIM TheString AS STRING, EndString AS STRING
INPUT Please enter some:, TheString
TheString = LTRIM$(RTRIM$(TheString))
IF LEN(TheString) = 0 THEN GOTO Again
GOSUB reversestring
PRINT This is it, reversed: ; EndString
PRINT
EnterAgain:
PRINT Do you want to enter some text again? (y/n)
INPUT (y/n):, choice$
Choice$ = LTRIM$(RTRIM$(UCASE$(choice$)))
IF Choice$ = Y THEN GOTO Again
IF Choice$ = N THEN END
the program will only get here if Choice$ Y AND Choice$ N
GOTO EnterAgain
Reversestring:
this function can actually be made much better using FOR or WHILE
but since you havent had them yet, I do it with GOTO
14
15
NextChar:
CurrentPos = LEN(TheString)
EndString = EndString + MID$(TheString, CurrentPos, 1)
CurrentPos = CurrentPos 1
decrease CurrentPos with 1
IF CurrentPos <> 0 THEN GOTO NextChar
RETURN
EXERCISES
Exercise #1: Make a kind of quiz. Show about 20 questions and at the end how many you
had guessed wrong.
Exercise #2: Make a program that counts the number of e or E in an entered string, and
shows that number.
Exercise #3: Make a program which asks the user to enter as much values the user would
like to, then calculates the average of the numbers.
Exercise #4 (HARD!): Make a text adventure. If you dont know what a text adventure
game is, try downloading Neptune Caverns at www.nemesisqb.com.
15
16
True
True
False
False
False
False
XOR
True
False
True
False
True
False
True
False
OR
True
False
True
True
True
False
True
False
EQV
True
False
True
True
False
False
False
True
IMP
True
False
True
True
True
False
False
True
NOT
True
False
False
True
These schedules are called TF-tables which stands for True-False Tables. In these
schedules you can see what an operator returns when evaluating the criteria. As you already know,
an If-statement is only run if the criteria is TRUE. So if the criteria is 5 = 5 then this will be TRUE
because in this case, five will always be five. However, when you use 2 or more criteria, youll need
to specify the link between the criteria. E.g. does every criteria has to be true? Then use AND.
Heres some code to get used to it:
A = 1
B = 2
C = 3
D = 4
IF (A = 1) AND (B = 2) THEN
this will only be run if A is equal to 1 AND B is equal to 2.
END IF
16
17
IF (A = 2) OR (C = 3) THEN
this code will only be run if one of both criteria is true, or
when both are true. So this code will be run when:
A = 2 and C <> 3
A <> 2 and C = 3
A = 2 and C = 3
so or is very flexible.
END IF
IF (C = 3) XOR (D = 3) THEN
this code will only be run if one of both criteria is true.
if both are true, this is not run (also when both are false).
So this code will be run when:
C = 3 and D <> 3
C <> 3 and D = 3
END IF
IF (D = 4) EQV (A = 1) THEN
this code will only be run if both are true, or both are false.
So it will be run when:
D = 4 and A = 1
D <> 4 and A <> 1
I seldom use EQV though
END IF
IF (B = 3) IMP (A = 1) THEN
this code will be run when both are true, when both are false
or when only the first one is true (if the second is true and
the first is not, this code is not run).
So when:
B = 3 and A = 1
B <> 3 and A <> 1
B = 3 and A <> 1
Never use it often though
END IF
If youd studied the TF-Schedules well, you would have noticed one thing. About the
NOT operator. The difference is that, AND, OR, XOR, EQV and IMP are binary-operators, and
that NOT is an unary-operator. What does this mean? Well its actually very simple. The binary
operators link 2 criteria together, while unary operators link only 1. So NOT only links 1. But how?
Simple, NOT turns around the value of all inner values. Example:
IF NOT(A = 5) THEN
this code is only run if A is not equal to 5. If A = 5 then the
expression between the brackets is true, because A = 5. Then not
turns around that value, so it is converted to false. Also, when
A = 4, the inner expression is false, because A = 5 is false
because A = 4, so not converts false to true, and the if-clausule
is run.
END IF
IF NOT(A = 1 AND B = 2) THEN
this code is run if the inner expression is false (not converts
17
18
false to true). In the text above about AND you can find out when
the inner expression will be false.
END IF
Till now, I kept it easy. But you can also imagine that sometimes, people need very complex
structures. When using more than 1 binary operator, you should also apply brackets to your code so
the QB IDE knows which binary operator to evaluate first. Heres a very complex example:
IF (((score = 200) AND (level = 5)) OR ((deaths = 10) EQV (units >
200))) AND (NOT(U = 9 IMP kills < 1) XOR (skill <> 5)) THEN
find out yourself when this code will be run!! :-D ;*)
END IF
19
20
The example above was dealing with the difference between Do Until and Loop Until (what
will be explained now is the same for Do While and Loop While). As you could have noticed when
running the program, from the first loop it says 1 and from the second loop it says nothing. This
phenomenon can easily be explained, lets just start at the first loop (I show you what the program
thinks).
Line 1: aah, a new variable called I. Store value 1 in I.
Line 2: Print From the first loop to the screen.
Line 3: aah, the start of a Do-Loop.
Line 4: Print I to the screen.
Line 5: hrrmm, Loop until I = 1, well, I is equal to 1 so lets exit the loop.
Line 7: Print an enter and the text From the second loop to the screen.
Line 8: Start of a Do-Loop, and since the loop must be exited when I equals 1, and since still
I equals 1, I wont run the loop and will jump immediately to the Loop the Do belongs to.
Line 10: I jumped from Line 8 to Line 10.
It should be clear now, if not, play some with the Do-Loop :*). It will be clear to you in no
time. And if you still dont understand after playing with it, heres some very short explanation:
When the program encounters a Do-Loop Until, the program first runs the code, and at the
Loop Until it checks if the expression is true, if so, exit the loop, else, loop again. But when the
program encounters a Do Until-Loop, it first checks if the expression is true, if so, exit the loop,
else, loop the loop, and when it arrived at the Loop, it jumps back to the Do Until and checks again,
if the expression is true now, the program will jump forward to the Loop it came from and goes on
from there.
NEXT counter
WHILE [expression]
WEND
21
Concerning Do-Loop, you can only specify 1 expression per routine, so you cant make a
Do While-Loop While or a Do Until-Loop While (for example).
Immediately exits the first specified loop. The loop of that kind is exited if this
command was in one of them.
CHAPTER PROGRAM
DO
CLS
PRINT Prime number calculator!
PRINT By Mr. X
PRINT
PRINT This program calculates all prime numbers up to
PRINT a number n (N > 10)
N% = 0
21
22
WHILE N% <= 10
INPUT Please enter n:, N%
WEND
PRINT
PRINT 1
PRINT 2
FOR primec = 3 TO N% STEP 2
step 2 because only odd nrs.
Dividable = 0
FOR primed = 2 TO primec 1 STEP 1
IF primec / primed = INT(primec / primed) THEN
Dividable = 1
EXIT FOR
END IF
NEXT primed
IF Dividable = 0 THEN PRINT primec
NEXT primec
PRINT
PRINT That were all.
PRINT Want to see more?
K$ = a
DO
INPUT (yes or no):, K$
LOOP UNTIL LCASE$(K$) = yes OR LCASE$(K$) = no
IF LCASE$(K$) = no THEN EXIT DO
LOOP
EXERCISES
Exercise #1: Make a program that can calculate the facultaty of an inserted number. If you
dont know what a facultaty is, e.g. the facultaty of 5 is 1 * 2 * 3 * 4 * 5 = 120. The facultaty of 10
is 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 = 3628800.
Exircise #2: Make a program that can calculate perfect numbers. A perfect number is a
number of which the sum of all dividers is equal to that number. E.g. 28 is a perfect number,
because the dividers are: 1, 2, 4, 7, 14. And the sum of the dividers is again 28!
Exercise #3: Make a program which can calculate combinations. (For readers with a Ti-83,
the possible combinations can be calculated with nCr (math-prb)). The user must be able to insert
the range and the length. E.g. if the user enters a 3 for range, only the numbers 1, 2 and 3 will be
used for cominations. If the user enters a 4 for length, the program calculates all possibilities with
length 4. So 1111 and 1321 are 2 of the possible combinations.
Exercise #4: Easy one. Make a program which can calculate:
n
i.
i=1
Which means this: 1 + 2 + 3 + 4 + 5 + + n. So calculate the sum of all positive integers up to and
including n.
22
23
CATALOGUE
Every command, function, keyword, (simply everything) which I wrote about is in this list.
Here you can find every keyword which is dealt in this part.
AND
AS
ASC
CASE
CHR$
CLS
COLOR
DIM
DO
DOUBLE
ELSE
ELSEIF
END
EQV
EXIT
FOR
GOSUB
GOTO
IF
IMP
INPUT
INTEGER
IS
LCASE$
LEFT$
LEN
LOCATE
LONG
LOOP
LTRIM$
MID$
NEXT
NOT
OR
PRINT
REM
RETURN
RIGHT$
RTRIM$
SELECT
SINGLE
SLEEP
SPACE$
STEP
STR$
STRING
THEN
TO
UCASE
UNTIL
VAL
WEND
WHILE (expression-waiter)
WHILE (loop-command)
XOR
AFTERWORD
QuickBASIC-Tutorial Part I: Beginners & Newbies Edition
By Neo Deus Ex Machina
Member of the Blind Coding programming team
http://www.blindcoding.cjb.net
2002-17-10
Thanks to all members of the Blind Coding programming team:
AetherFox
BlueKeyboard
Mofu
Neo Deus Ex Machina