QBASIC Techniques
QBASIC Techniques
QBASIC Techniques
QBASIC techniques
For Beginners
11/13/2007
Pravesh Koirala
Credits
Pravesh Koirala (Hey I wrote this book!)
Prasanna Koirala (For inspiration and support)
Family members (For their support)
Someone else (Cause he is the real source of inspiration for me. I don’t want mention his
name)
Diwaker Jha (A fantastic person, nice friend, and the one who lead me deeper into
computers)
More Reading
Finished this Book! Please write a feedback to me. Your feedback will prove to be an inspiration to
me. If you want some more QBASIC stuffs then you can always search internet. Also, I plan to write
next part of this book as “Advanced QBASIC Stuffs” covering concepts like File Handling, Modular
programming, Graphics and Sound, Game programming in QBASIC etc etc etc. Let’s hope that it will
be completed soon. Thanks!
So next time onwards you will always respect Qbasic, will you? Anyways, since you have learnt the
calculating concept, you have rights to ask me that why this is important? For its answer you must
wait for the next chapter. If you still don’t have a proper idea about this topic then I urge you to read
it again and again because this is very important chapter that teaches you a good formula for neat
programming.
5) If you are writing a lengthy and complicated program then try to break it into small sub
procedures.
6) Always select the variable name that is most suitable for the calculation and easy to
remember. E.g. If you want store average marks of students in a variable then try to use
variable like Avg_Student or Avg_Mark etc.
7) While using Print or Input statement always try to give a proper message to the user
otherwise your program couldn’t interact with the users well.
*Using Help
QBASIC is provided with a manual. If in your program anything goes wrong then you are prompted
with an error message. If anything like syntax error happens then you can always check out the
manual. Just place the cursor below the problem area and press F1 key. That will display the help
related to that very command.
*The translator
You will find that in most of the topics I have mentioned about translator. I think many of you know
about it. If you don’t then Good! As I mentioned earlier, computer is a digital machine and it knows
only 0 and 1. Then the question comes that how does the computer follows our English instructions
like Print, End, CLS etc? It’s because the English command that you type on the QB editor, is
translated to 0 and 1 via either a Compiler or an Interpreter. These Compiler and Interpreter are
called translator software.
*Statements
The statements, in QBASIC, are the operations that give some result. E.G.
a=4, b=b*5, Print “hello” etc
A variable has its two characteristics, its type and data hold by it.
Output:-
3
0.03
Output:-
3
2
What! A 2! But hey, I said that I want to print a 2.03. Maybe the translator has gone mad! No, it is
not the translator. As soon as you run your program, the translator translates the program to
machine codes from top to bottom. The translator is instructed that the variable A is an integer and
so, it occupies memory space for integer. Up to step 20 it runs smoothly but as soon as it encounters
the next step i.e. (A=2.03) then it thinks for a while, “Umm, let’s see what we have, A=2.03. What?
Oh god! What’s the programmer trying to do? First he says reserve the space for integer and then
wants to keep a floating value 2.03. He must have gone mad! Anyways better I store only the integer
2.”
And so the translator doesn’t store any floating value and variable A
becomes 2. So Einstein, from next time onwards never try to store a wrong value in a wrong type. It
can really annoy the translator and moreover can effect a mathematical calculation.
Example-1 Example-2
CLS CLS
A = “HELLO” Dim A as String
Print A A= “HELLO”
End Print A
End
What do you think what is the output of Example-1? If you thought about an error then you got it!
Certainly, there will be an error i.e. “Type Mismatch”. Well, previously the translator did correct our
error because it was related to numerical type mismatch but as I told, the string is completely
different from the number in relation to its storing process. Do you know something about ASCII?
You must know! There is a standard code for each of character. So when you store some string
values then RAM will not actually store the character but its ASCII instead.
But in Example-2 we have
already instructed the translator that we need a space for string value represented by the variable A.
So there will be no any complications.
*Following are some of the signs that can be used for different var(variable) types
i) $ String
ii) % Integer
iii) ! Single Floating Point
iv) # Double Floating Point
v) & Long Integer
I am sure that out of these steps you are familiar with the first two. So, lets learn how to declare a
default variable. By default, in Qbasic, each variable is a numeric variant unless declared using Dim
statement or using signs. But we can declare any other type as default according to our wish using
the DEF-Type keyword. E.g.:- DEFStr A-Z
Lets break the statement. DEF + Str + A-Z are our results. Clearly, DEF is a function used to declare
the default type. Str is acronym for String and A-Z is the range. What this function does is, it declares
all the variables from A to Z as String unless separately declared using Dim or any sign. Let’s have a
short example.
CLS
DEFStr A-W ‘Now lets declare all variables from a to w as string
Dim C as integer ‘Lets separately declare C as integer
V= “Hello World!” ‘Put “Hello World” in variable V
C=8 ‘Put 8 in C
D! = 9.09 ‘Store 9.09 in D!
Print V , C ,D% ‘Print all vars
End
Understood? What! No? Ok ok don’t panic, Lets deal it in detail. We declared all values from a to w
as string. So, we need not use $ sign with the variables now onwards. But wait, we also declared c
separately as an integer. And why we have used D! while storing 9.09 in it? So confusing right?
Answer is, we are storing an integer value in c i.e. 8. But since the default type is string, thus, Qbasic
would have treated it as a string and you know that 8 is not a string so there would have an error.
For D we have stored 9.09 and again the QB would have tried to store it as a string but since we
provided it with the symbol ! so the translator will now store it as a single precision. Clear as mud,
right? ☺
*CONSTANTS
Since you are now clear with the variables then lets head towards Constants. You already know that
variable is a location in memory that stores a data. And Constant is that very data which is being
stored. E.G.
A% = 5
B% = 10
With this simple command, the following things happen inside the memory.
A
0 0 0 5 0 0 0 0 0 0 0 1 0 1
0 0 0 0
0 0 0 10
RAM B Bits
I think that since you began to learn computer, you were taught about 1
byte is equivalent to 8 bits. If you were not quite clear about that then the figure illustrates it all. Bit
is the smallest part of memory. And the group of 8 bits make 1 Byte.
Every thing is alright except that all other locations(or bytes) are 0. Do you know that the memory
stores the data in form of electric charges?
Now when you store 5 in A then translator occupies a memory location and system charges the
memory electrically and 5 is stored in form of electricity. But consider this small program.
CLS
Dim C as integer
Print C
End
What do you think about the output? Certainly, there will be a zero. You did declare space for C
but you forget to store any value. It means that the memory won’t be charged and as a result you
will get a big 0. But in other programming language like C++, the default value of a variable is
undefined.
Output
7
I think that I need not mention what happened here.
For updating variable repeatedly, we must use it with loops. Loops are described in forthcoming
chapters.
A simple program to ask user two value during runtime and print their product
CLS
Input “Enter two values separated by a comma ”;a , b
Res = a*b
Print “The product of the two values is ”;Res
End
Output
Enter two values separated by a comma ?2,3
The product of the two values is 6
Equality
When you test a value in QBASIC then either you will get true or false. True represents 1 whereas
False represents 0. Any non-zero value is considered as True in QBASIC.
If.. then..else command can also be defined through its name. Its syntax is:-
If (condition=true) then statements1 Else statements2. The conditional operators are greater
than(>), less than(<), equal to(=), greater or equal (>=), less or equal (<=), not equal(<>). All the
above conditional statements can be easily understood because we have been using it in math since
childhood, haven’t we?
If.. then..Else command is of two types. Single line and Multiline. The above
you saw was single line. Lets consider a multiline one.
CLS
Input “Any number ”;no
Res = no mod 2 ‘Divide no by 2 and check the remainder
If res=0 then ‘If remainder is 0 or number is perfectly divisible by 2 then
Print “The number you entered is even”
Else
? “The number you entered is odd” ‘remember “?” stands for print
End if
End
Output
Any number ?8
The number you entered is even
Multiline If statement has following syntax
If condition is true then
Statements
Else
Statements
End if
Always remember that the multiline if statement should be terminated by
End If statement. It tells the translator that the condition is over and normal operation can be
carried out. Mod used in the program is an abbreviation for modulus. It simply returns the
remainder value. 8 mod 2=0, 8 mod 3=2 and 2 mod 3=0 etc.
Multi conditioned if statement is also
equally important. It is generally used to test multiple conditions. For example, if you simply want to
operate two numbers (addition, multiplication, division, subtraction etc) then you need to first get
two values from the user and also what he wants to do with that two values.
Now lets see what happened here. First we were prompted to enter
two values according to our program. Then we were provided with a list of available actions. As we
chose the value 3 (Multiplication) then the program tested that what we entered. First is checked
whether the value we entered is 1 or not. Since we entered 3 and 3 is not equal to 1 sot it moved
ahead skipping the statements for that condition. It encountered next condition and checked that
whether we entered 2 or not. Again it couldn’t find 2 in our choice and so it moved ahead skipping
the statements that we wrote for that condition. At next condition, it compared our value with 3.
And since we had entered 3, it carried out the statement written for that condition i.e. a*b. And it
straightly moved towards the End if statement without checking for Else part. Now when it
encountered the End if statement, the translator was informed that condition check is over and now
it can perform normally. Then it carried out the next line in which it printed out the results. And after
a long process (about a picoseconds or 1 trillionth of a second) our program ended. Phew!
A new
command that you encountered here is the Goto command. It simply tells the translator to execute
the program from the address provided (also called labels). A label can be alphanumeric (containing
both alphabet and numbers) followed with a semicolon. We will discuss about it in forthcoming
topics.
Now when you run this program and enter your age, the computer
tests it whether you entered less than 0 or equal to 0; or greater than 120. If so then computer
generates an error message “Do you think I am a fool?” and redirects the translator to move to the
address start:. The translator searches for the address and there it is in the second line. So, it moves
to that line and starts the execution again. When you enter a valid age i.e. 30 then again it checks
whether the age is valid or not. Since it is valid, so again it checks another condition whether the age
is greater than 0 and less than 18 or not. 30 is greater than 1 but it is not less than 18. So it again
move towards another condition skipping all the statements in between. At the next condition, it
encounters the condition i.e. whether your_age (30) is greater than or equal to 18 and less than 60
or not. 30 is greater than 18 and also less than 60 so it executes all the statements of that condition
and as a result “You are grown up” is printed in our screen. After that it encounters another
condition which is also false for it. So, the program ends.
Program 2
CLS
Dim letter as String
Input “A letter in lower case “;letter
If NOT(letter = ”a”) then
? “You have not entered a”
Else
? “You entered a”
End if
End
Output
A letter in lower case ?b
You have not entered a
It is quite clear, isn’t it? When you enter a letter (b) that is stored in
the variable letter which is of string type. Now the translator checks if the letter is not equal to a.
Yes, we entered b and b is not equal to a. Thus, it executes the statements and prints “You have not
entered a”.
carried out from the same point in the main program that passed the control to subprogram. But
Goto just redirects the translator to another location in the same program. E.g.
CLS
Input “two different values ”;a, b
Gosub addition:
Print “The sum of the numbers is”;res
End
Addition:
Res = a + b
Return
I think you are clear enough, aren’t you? Ok then let’s try some exercises.
1.) Write a program that asks user for 3 values and finds it sum and checks whether its sum is
greater than 100 or not. The program must inform the user about the sum of the numbers
and also should tell them whether it is greater than 100 or not.
2.) Write a program (W.A.P.) to ask user for his marks in 5 subjects. Calculate the total, the
average and also check whether he is pass or fail or distinction.
For pass:- Average above 39
For fail :-Average below 40
For distinction:- Average greater than or equal to 85
Loops
Imagine that you want to print “Hello Computer” 5 times. Then you would have written it in this way
CLS
? “Hello Computer”
? “Hello Computer”
? “Hello Computer”
? “Hello Computer”
? “Hello Computer”
End
Quite easy, right? But then how would you print the same
thing 100 times and 1000 times. Ah! So its not that easy, right? So in such situation we can use a
loop. A loop is the process of repeating a set of statements multiple times. Consider the same
program in this way.
CLS
Printing_Time = 1
Loopstart:
Print “Hello Computer”
Printing_Time = Printing_Time +1
If Printing_time <=5 then Goto loopstart: ‘Put there 100 instead of 5 and you will get it 100 times
End
So, which one is smaller? Well I know that your answer will
be, “both”. Yes, they both are equal but when you will have to print the same thing 100 times then
the first one would have been 102 lines but the second one only 7. So, tell now, which one is more
smaller and easier? Well then since loop is so important so we must learn it. Get ready!
E.g.
CLS
A=1 ‘Initialize the counter (variable)
Loopstart:
Statements
A=A+1 ‘Increase the value of counter
If A <= 20 then Goto loopstart: ‘Test whether the desired no of loops has been made or not i.e. 20
‘End of loop
End
This is the general concept of looping. However, loop is not only made according to variable
but also according to certain conditions (Discussed later).
*For….Next Loop
It is completely based on the value of counter. For…Next is the most common and convenient
method of loop. Its syntax is:-
Should I explain it? Well, as you wish. Consider program 1. Simple, isn’t it? We just
took a variable I and initialized with it 1 (Stored 1 first). Then we placed our statement. Since we
didn’t mention the step value, thus, computer automatically assumes it by 1 and updates the value
of I by 1. Now it became 2. Now at the Next statement, computer checks whether I (2) <= final
value(5) or not. Since it is not, so the translator is redirected to the statement just after the For
statement. Now when it loops 5 times then the value of I becomes 6. Since 6 is neither less nor equal
to 5, so the translator didn’t loops and carries out other statements.
In program 3, the step value is
mentioned and is negative, so the translator will treat everything same except the looping condition.
When it reaches the next I statement, then it checks I >= final value instead of I <= final value. This is
the only difference.
.. up to 9 term
CLS
For I = 1 to 9
Print I ^ 2
Next
End
Really a smart way; right? So what is the main difference between these two
programs. They both have a same logic and a same result but the only difference is that in second
one, the looping variable has been used for doing the same work instead of another variable. Cool,
isn’t it?
E.G.
CLS
Input “ A number “;no
While no <> 0
Print no
No = no\10 ‘ “\” is used for integer division
Wend
End
The While loop will be executed until the value of the no becomes 0. If we
take 567 as no, then following will be the output.
567
56
5
‘\’ is a symbol of integer division. It means that it only gives the quotient
value. E.G 345/10 = 34.5 but 345\10 = 34.
*Infinite Loop
Infinite loop resembles a loop which is never ended. Consider these two programs.
CLS CLS
For I = 2 to 30 start:
Next I Goto start:
End End
The For loop in program 1 is going to be executed 29 times. And after that the program is going to be
terminated. But is 2nd program, the loop is never going to end. Each time the translator encounters
Goto start: command, it moves to the start label and again it encounters Goto start. In this way the
program never ends. However you can press Ctrl + pause button during the run time to stop
execution of the program.
CLS
Start:
If inkey$ = “a” then End
Goto start:
This is an infinite loop but when during the execution you press ‘a’ then the value
returned by inkey$ will be ‘a’ and according to the condition, the End command is executed and the
program terminates. Inkey$ is particularly used while making a Qbasic game. But when you press
some special key like Up arrow, down arrow, Function keys etc then inkey$ generates two byte
string instead of a single. The two byte string consists of 1st char space(“ ”) followed by a 2nd char.
E.G.
CLS
Dim a as string
Start:
a = Inkey$
if a <> “” then print a
Goto start:
Fine, this simple command will tell you about the codes for all keys. But hey
wait, how are we going to stop it? It will continuously run since it is an infinite loop. You can either
insert condition like ‘IF a = “e” then end’ or simply press Ctrl + Pause ( or Break).
*Exercises
1.) Write a Program to print 1 2 3 4 5 6 7 8 9…. Up to 100
2.) Investigate this program.
CLS
Dim sprite as string
Sprite = chr$(1) ‘Equivalent to a ☺ smiley
For I = 1 to 100
Print Sprite
For j = 1 to 2000 ‘Dummy loop
Next J
Next I
Well that dummy loop is just a waste of time so that you can see the results more easily. After all
we can’t see that fast as a computer. Ok just enjoy all QB stuffs and see you in next chapter.
*Types of Functions
There are many types of functions in mathematics but we shall be only dealing with those important
for us in QB. Let me list some of the functions that I remember.
• String Functions
• Trigonometric Functions
• Numerical Functions
• User-defined Functions
Blah, blah and blah (etc).
As I said earlier there may be some other functions but hey I didn’t mention them. What can you
expect more? This book is intended for beginners. If you want more then search it yourself.
Out of these functions, User-defined functions is covered under modular programming concept. We
shall be dealing with String Functions and Numerical Functions in detail. But let’s have some quick
concept about Trigonometric Functions.
*Trigonometric Functions
Trigonometric Functions is only meant for those programmers that have some knowledge about
Trigonometry. If you don’t know about it then you can skip it.
*String Functions
I told earlier, String functions are quite important. So we shall be discussing it in detail. But
remember, you can have command over QBASIC only when you practice more and more. String
Functions are generally determined if they give a string expression as a result but I have included
some functions that are non-string but they do work for String Manipulation.
In the first program, the result is “11” but in the second program, the result is 2. So, string
and numbers are different. Sometimes, you need to convert a string to integer, then you can use the
VAL Function. Like in this program,
CLS
Input “A number”;A$
A=Val(A$)
Print A,A$
End
If you give input as 20 then it will not be stored as number, instead it will be stored
as string as “20”. But when you use VAL function then that “20” is converted as numerical 20. But
while printing the values your output will be 20 20. This indicates that both string and numbers are
printed in the same way only their storage and operations differ. The syntax of Val is
Val (string)
And it will give you a number equivalent to that string. But if the first character is non-
numeric then VAL returns 0.
Val(“20”) ‘gives 20
Val(“476as”) ‘gives 476
Val(“Pra345”) ‘gives 0
Hope you understood about val. Now let’s deal the STR function.
Like you converted string to number, similarly you can convert number to string using the STR
function. Its syntax is:-
STR$(number)
Remember, since it has $ sign, so it indicates that the return type is string.
Obviously, it returns string. That’s what we dealt above.
CLS
A=8
B=9
Print A+B
A$=Str$(A)
B$=Str$(B)
Print A$+B$
End
Output
17
89
Got that in your brain box! Its easy, isn’t it? Though the output seems to be
like number but actually the first one is only a true number second one is string.
String Manipulation
*Mid$ Function
Mid$ is a very useful and essential function. Its syntax is :-
Mid$(string value, starting position, length)
Umm, that’s okay but what does it do? It simply returns the length characters from
the starting pos of string value. Consider these operations
Mid$(“Pravesh”,3,2) returns “av”.
Mid$(“USA rulz”,2,4) returns “SA r”
Mid$(“ pp”,1,1) returns “ ” (one space character)
Hope you got that. Mid$ is very much essential so I suggest you go thru the text
quite seriously. Mid$ can be combined with loops to generate interesting string pattern. You may
also need to separate each character from the given string so just try to use it in loop.
Program-1
CLS
Temp$ = “Hello”
Temp_length = LEN(Temp$)
For I = 1 to temp_length
Char$ = mid$ (Temp$,I,1)
Print Char$
Next I
End
Output
H
e
l
l
Program-2
CLS
Temp$ = “Hello”
Temp_length = LEN(Temp$)
For I = 1 to temp_length
Char$ = mid$ (Temp$,1,I)
Print Char$
Next I
End
Output
H
He
Hel
Hell
Hello
Observe that how the changing value of I combined with mid$ function to
generate such string patterns. Also we needed to loop only that many times equivalent to the length
of string. Thus, we used the Len Function. You will get used to it under 3 or more topics.
CLS
A$ = “Rani”
For I = 1 to Len(A$)
Print left$(A$, I)
Next I
Output
R
Ra
Ran
Rani
If you understood that then you should have no serious problem understanding the
Right$ function. It also does somewhat same as left$. It just returns the rightmost length characters
of the string value. Anyways have its syntax and some EGs.
Right$ (string value, length)
The Asc function returns the ASCII value of given character. Its syntax is Asc(“character”).
? Asc(“A”) returns 64
Since ASCII code for A is 64 so the function returns 64. But remember ascii for A is not equal
to ascii for a.
The Chr$ function just does opposite of what Asc does. It returns the character represented by the
given ascii value. ? Chr$(64) returns “A”.
*Instr Function
Instr function is also quite easy but useful function in QBASIC. Its syntax is INSTR ([start pos,]
string1,string2]). What it does then? It simply finds the occurrence of string2 in string1. E.G
? Instr(“Hello boy”, “llo”) returns 3 ‘llo starts from in 3rd position in string “Hello boy”
?Instr(“Now I Now”, “Now”) returns 1 ‘Now starts from 1st position in string1
?Instr(4, “Now I Now”, “Now”) returns 7 ‘Now starts after 4 and at 7th position in string1.
*Space$ Function
Space$(number) just returns number spaces. It can be useful to comparing a string with spaces or
something like that. You can store the value into any variable. A$ = SPACE$(145) returns 145 space
characters in variable A.
That’s all for String Functions in QBASIC. I know that there are still some missing but as I said “There
is much delight in exploring rather than knowing”.
Numeric Functions
ABS
Abs(number) returns the absolute value of a number. ? ABS(-5.6) returns 5.6
SGN
SGN(number) is used to determine the sign of number. If number is positive, SGN returns +1; if
number is negative, SGN returns -1; if number is 0, SGN returns 0.
? SGN(-45) returns -1
? SGN(68) returns 1
SQR Function
SQR(number) returns the square root of the number. ? SQR(25) gives 5
INT Function
Int(number) returns the largest integer that is either less than or equal to number.
? Int (12.56) returns 12 (12 is the largest integer that is less than 12.56)
? Int (-40.55) returns -41 (-41 is the largest integer that is less than -40.55)
FIX Function
Fix(number) just removes the decimal part and returns integer part of the number.
? Fix(9.88) returns 9
? Fix (-3.90) returns -3
CINT Function
CINT(number) rounds off the integer number.
? CINT(9.8) returns 10
? CINT(5.3) returns 5
number for you using the RND function. RND generates a number greater than 0 and less than 1. You
can always extend the number to a range by using the formula INT (RND * upper limit) + lower limit.
E.G.
CLS
Randomize TIMER ‘Initializes the randomizing counter according to the value of Ticks of CPU
? “I have a number in my mind”
? “It is a number between 2 and 10”
? “Enter your guess”
Input number
MyGuess% = INT (RND * 10) + 2 (The upper limit is 10 and lower limit is 2)
Congratulations!!!!
Congrats dude, you just completed the book. I hope you found it useful. But if you still have unsolved
questions hovering around your mind then please feel free to mail me. I shall try to reply positively.
Any feedback from you will be appreciated. Bye then!!!!!
The END