You are on page 1of 29

QBASIC techniques for beginners

QBASIC techniques for beginners


QBASIC techniques for beginners
QBASIC techniques for beginners
QBASIC techniques for beginners

QBASIC techniques
For Beginners
11/13/2007

Pravesh Koirala

QBASIC techniques for beginners


QBASIC techniques for beginners
QBASIC techniques for beginners
QBASIC techniques for beginners
QBASIC techniques for beginners
QBASIC fundamentals 10/12/2007 2

About the Author


Name:- Pravesh Koirala
Currently:- Studying
Interests:- Computer programming, Electronics, Football and Cricket
and reading Books
Country:- Nepal
Mail Address:- pro_science108@yahoo.com
Language learnt:- QBASIC, Visual Basic, Visual Basic.NET and C# (learning)
Programming interests:- Designing complete applications, Games etc

Who can be a good Friend


Anyone who is interested in computer and programming in any language can
be a good friend.

Views From Author


Hello everybody! Ok now, actually I thought to write this book keeping in mind, the problems faced
by the beginner programmers in Qbasic. Qbasic is an excellent tool to develop a programming
concept in students. Actually it was developed for that very purpose only. But in spite of its
simplicity, students often feel some problems during their studies. I don’t know its exact reason but I
guess that the course books just focus on the theoretical studies and don’t actually develop the
concept in students. A programming just doesn’t mean to find “LCM, HCF, Factorials, Prime
numbers” and other calculations but the real meaning of programming is to directly communicate
with the computer and make it perform some work.
I, being really interested in programming, had some explorations on the net and gathered some
basic techniques of this programming language. And seeing the complications of the students during
the course, I was inspired to write this booklet. Frankly speaking, QBasic is not that hard. But
programming can be really a challenge. QBasic just develops a basic concept, it is not that standard
language and programming is not only limited to Qbasic. You will find a lot more in the field of
computers; this is just a beginning step. And also it depends on you that how much you want to go
deeper into the programming concept. Anyways, I hope that you find it useful and handy. If you still
face problems after completing this book then I am always in this world. You can just contact me at
my mail address i.e. Pro_science108@yahoo.com. Hope you will enjoy it because I have, my best,
tried to use simple language and techniques. And yes, being a student myself I can’t assure you that
this booklet is 100% error free. But I have tried my best to correct all the errors like spellings,
grammar and others. What else can you expect from a student? If you could catch any of them and
point out the mistakes then you have got all sort of rights to contact me and inform me about those
bugs. Also, if you have some other suggestions for me then you are always welcomed. Don’t forget
to write a feedback.
Last but not the least, the legal stuffs ( Boring!). You can distribute this booklet to any of your
friends, students or your children (And please don’t forget to mention my small name, will you? ) but
please never try to misuse it for any commercial purpose. I hate these types of guys, you know!
©- Pravesh Koirala ( Can be distributed for non commercial purposes )

2 QBASIC techniques for Beginners by Pravesh Koirala.


QBASIC fundamentals 10/12/2007 3

Intended Audience (Who should read this book?)


I have written this book assuming that readers have some little previous knowledge of the
programming language (QB). But complete beginners can also take benefits from this book. However
those with little previous knowledge can have advantage. The perfect scenario will be that you have
already learnt QBASIC but you don’t quite know about how to use the functions and you haven’t got
the programming language well.
This book has nothing related with advanced topics in QBASIC like
Modular programming, File Handling, Graphics and Multimedia etc. If you have already learnt the
basic techniques then you got this book accidentally and should distribute to one who needs it more.

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!

3 QBASIC techniques for Beginners by Pravesh Koirala.


QBASIC fundamentals 10/12/2007 4

Chapter-1 (Introduction to QB)


Well ready for some QB lessons. Ok now try to learn some fundamentals before actually starting
programming concept. Qbasic is a character programming language. (What does it mean?). It means
that you cannot implement the windows components like command button and scroll bars that you
generally use. Anyways no matter what it is but we have to learn it right? Now you will find that you
need to calculate a value like adding, subtracting, divisions etc even for a small program. If you have
already programmed a simple application then you ought to know that for multiplication you follow
the following steps.
QBasic calculation Human Calculation
CLS 3 x 4 (3 times 4 or 4 times 3)
A=3 i.e. 3+3+3+3=12 or 4+4+4=12
B=4 thus, 3 x 4 = 12
Print a*b
End
Umm, let’s think now. What is the difference between this calculation and our human calculations?
We have generally mugged up the table of up to 20 even more. Thus it’s in our mouth that 3 into 4
equals 12. But the story is different in case of QBasic. First we store 3 in A and 4 in B and we used
print a*b. I hope you know the simple functions like Print, CLS and End, If not then wait for Chapter 3
☺. Anyways let’s see what happens in this case. First of all the value 3 is stored in one location of
Ram and value 4 in another location. Now it will straightly travel into the processor’s ALU
(calculation unit). Since, computer is a digital system and it have no techniques like ours, thus, first
of all it converts 3 and 4 into binary that is 11 and 4 is 100. Now it will perform binary multiplication
(I hope you do know the binary calculations) there and store the result into its memory (No, not
RAM, CPU have its own store place called registers). Then it converts the result into decimal and
sends the value into a location in Ram (yes, another location!) and then Qbasic access it and prints
into the screen. Phew! A long process, isn’t it? If you were said to do it then I think it must cost you
minimum 50 seconds or more for the longest one. But imagine, the computer does it in a trillionth
part of a second, isn’t it amazing! Let’s have a quick graphical recap.
A
3
Qbasic
B RAM CPU RAM Screen
4
Values are stored Calculations Result stored Output Shown

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.

*Some good practices


Here are some of the good practices that you can use in your program.
1) Always declare the variables with Dim command before using them. (More details in next
lesson)
2) Always try to write remarks in your program using REM function or ‘ character. Writing
remarks makes it easy to understand your program for yourself and other programmers.
3) While writing conditional statement and loops first write their opening and closing
command and then insert the statements in between them.
4) Try to select the most suitable loop for your program.

4 QBASIC techniques for Beginners by Pravesh Koirala.


QBASIC fundamentals 10/12/2007 5

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

5 QBASIC techniques for Beginners by Pravesh Koirala.


QBASIC fundamentals 10/12/2007 6

Chapter-2 (Variables and Constants)


Let’s recall the simple program that we made in the first lesson.
CLS
A=3
B=4
Print a*b
End
Now, I think that you do know about the variables and constants but anyways you will have a clear
concept about those in this lesson. Lets see “A=3” we already dealt that what it does. It simply stores
the value 3 in a location in RAM. Then what is the importance of “A”? Its answer is, the location in
which the value 3 will be stored in the RAM will be represented by the keyword “A” so that when
you want to retrieve the value of A from Qbasic then the system will search all the values stored and
used by the program. Then it will have three locations A, B and another one (I know that you are
amazed but yes there is another location with a value. What is it can you find? If you can’t then don’t
worry, I will tell you about it in the last part of this chapter). Within the three locations the system
will match the keyword that is A. Now when it confirms the value then it transfers it into the QB and
QB displays it into the screen.
Phew! Again a long process just to recall a simple value, isn’t it? Now think for a while, why in the
world is this process important and being mentioned? Imagine that you will try to retrieve the value
of one variable and then you get the value of another. This can really be dangerous and it is simply
not good. Well we are lucky that the computer does it all otherwise it would have been a tedious
task to manage all the locations and values.
And can you answer that why the hell “*” is used instead of “x” for multiplication. Answer is simple,
it is because you might want to have a variable “x” and this will create a lot of confusion. Well the
developers of the QB are really smart, aren’t they? While determining a variable following things
should be considered.
1) Variable can have alphabet from A-Z and digits from 0-9 and underscore “_”
2) Variables first character must be non numeric. E.G- pro10 (not 10pro)

A variable has its two characteristics, its type and data hold by it.

*TYPES OF THE VARIABLE


Consider,
A=3 and A=0.003
In both the cases, there is used a same variable A but there is a lot of difference between their types
A=3 represents that A is a variable used for storing an integer type value but on the contrary,
A=0.003 represents that A is used for storing a decimal or floating type value. And yes, each variable
has its own type that must be declared. The declarations can be carried out by the Function DIM.
E.g.:-
Dim a as Integer
Dim b as Long
Dim c as String
Dim a (5) as integer
Note the point that a, b, c are the variables and the keywords “Integer”, “Long”, “String” are their
types. The characteristics of the types can be found in any course book. I suggest you to go through
it. In summary, each variable has its own memory requirement.
Now the big question comes that though we haven’t declared the variables A and B in our previous
program, how does the program handles the memory for it? And the small answer is; all the non
declared variables are thought to be a numeric variant by the translator. But what is a variant?
Variant is also a type but it consumes comparatively a large space in the memory. So, it’s not a good
practice to use them more often. However, in small programs they can be used. EG:-

6 QBASIC techniques for Beginners by Pravesh Koirala.


QBASIC fundamentals 10/12/2007 7

*Non declared or implicit variables


E.g.:-
A=3
Print a
A=0.03
Print a
End

Output:-
3
0.03

*Declared or explicit variables


Dim a as Integer
10: A=3
20: Print a
30: A=2.03
40: Print a
50: End

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.

*String Type Value


A string type value resembles a character sequence of up to 32,767 characters and always kept
inside the double quotation in not only QB but in other higher programming language too. Strings
are handled differently by the memory (RAM). So, if you try to store string in a numeric variable and
vice versa then system will feel really . Let’s have an example.

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

7 QBASIC techniques for Beginners by Pravesh Koirala.


QBASIC fundamentals 10/12/2007 8

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.

*Signs used for types


Imagine that you are designing a small program and you don’t want to spend time writing
declarations for variables (However writing declarations is a good practice ☺.) Then you have the
options to use some special signs that will tell the translator about the types of the variable. E.g.:-
CLS
A$= “Pravesh” ‘Instead of declaring A as string you can directly use signs
Print A$ ‘But remember you must always assign the sign in the program with that variable
End

*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

*Declaring a default Type


Now think for a while. You want to work only with one type i.e. string. I mean that you want to use
only string variables in your program. Then there are three ways.
i) Declare all variables that you want to use as String
ii)Use sign $ for each variable
iii)Declare the default type as String

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

8 QBASIC techniques for Beginners by Pravesh Koirala.


QBASIC fundamentals 10/12/2007 9

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.

*Updating the value of constants during program execution


In QBASIC the value of constants can be updated during run time. Well, if it can be changed then
why is it named Constant? Strange, right?
Anyways, updating the value makes it possible to carry out different calculations. E.G
CLS
A=5
A = A+2
Print A
End

Output
7
I think that I need not mention what happened here.

*Updating Variable with loops

9 QBASIC techniques for Beginners by Pravesh Koirala.


QBASIC fundamentals 10/12/2007 10

For updating variable repeatedly, we must use it with loops. Loops are described in forthcoming
chapters.

*What was that another location mentioned earlier?


Well I mentioned about three locations at the start of the chapter but there were only two viz.
(namely) A and B. Then what am I gone mad? No certainly not, if I were mad then how could have I
wrote this book. Anyways, So what was that third location? The answer is, after the calculation of
3*4 the result i.e. 12 is also stored inside the RAM. So, it is also a location, isn’t it?
So, we came to the end of this chapter. See you in next chapter. Oh! I was about to
leave without giving you an information. See, how dumb I am! The thing that I wanted to inform you
was that I didn’t mention some more topics about the variable types like User-defined types.
Remember what I said earlier, it depends upon you that how deeper you want to go inside the
programming concept. So, if you want to explore more then just check out some other books and
explore. Otherwise, leave it!

10 QBASIC techniques for Beginners by Pravesh Koirala.


QBASIC fundamentals 10/12/2007 11

Chapter-3 (Programming Fundamentals)


The real programming starts from this chapter. Let’s first deal with some common QBASIC Functions.
*The CLS Command
CLS is an abbreviation for Clear Screen. As its name defines, it is used to clear the output screen.
CLS also have some parameters (Some values that needs to be given to the function to ensure
proper results). But CLS can be also used without it which clears the whole screen. If you want to
know about those arguments then discover yourself!

*The Print Command


Print command just prints the value of a variable or some message to the output screen. The two
different things to print should be separated by a “,” or “;”. By default the print command supplies
the carriage return (an instruction to computer to come to next line) unless used provided with ; at
the end. “?” can be used instead of Print command
CLS CLS CLS
A=5 A=5 A=5
Print A; “Is the value of A” ?A Print A;
End Print “Is the value of A”; Print “ Is the value of A”
Print “ Got it!” Print “Got it!”
Output End End
5Is the value of A Output Output
5 5 Is the value of A
Is the value of A Got it! Got it!

Analyze all the three programs and their output carefully.


There are many questions to be answered like:- In 1st program “5Is” is joined but in program 3, “5 Is”
is separate. Remember the space you give in the string message is also counted and printed.

*The End Command


End command is simply used to terminate the program. It deletes all the value of variables from
memory and closes all opened files and devices (Advanced topic). Another alternative of End
command is SYSTEM which ends the program and returns to the system as well.

*The Input Command


The input command allows user to input a value in variable during run time. You can give messages
to the user that will make it more user friendly. The value type that user inputs must be similar to
the variable type that is used to store the value. A “;” or “,” should be used to separate the different
parts of input statement. And multiple values can be entered. E.G:-
CLS
Input “Your name and age ”; nam$, age ‘Here name is string type so nam$ is used.
Print “Your name is”;nam$
Print “Your age is ”;age
End
Output
Your name ?Pravesh,19
Your name isPravesh ‘Consider that no space is used with the print command.
Your age is 19 ‘And space is given with another print command

So to clarify that what you want from the user, message


must be given in a proper way.

11 QBASIC techniques for Beginners by Pravesh Koirala.


QBASIC fundamentals 10/12/2007 12

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

*Conditional Statement (If..Then..Else)


Imagine that you want to test a condition that whether the age of the user is above 18 or not. Then
you can implement following codes.
CLS
Input “You age ”;age
If age>18 then print “You are adult” else print “You are not an adult”
End

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

12 QBASIC techniques for Beginners by Pravesh Koirala.


QBASIC fundamentals 10/12/2007 13

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.

The syntax of multi conditioned If statement is:


If (statement1) is true then
Operations
Else if (statement2) is true then
Operations
Else if (statement 3) is true then
Operations
Else
Operations
End If
Remember, End if should always be supplied at the end of the multi conditioned If
statement. E.g.:-
CLS
Start:
Input “Please supply me with two values”; val1,val2
Print “What do you want to do with these values? “
? “1.)Addition”
? “2.)Subtraction”
? “3.)Multiplication”
? “4.)Division”
Input “Enter your choice “;choice
‘Starting of the condition
If choice=1 then
Result = a + b
Else if choice=2 then
Result = a-b
Else if choice= 3 then
Result = a*b
Else if choice=4 then
Result = a/b
Else
Print “Please enter a valid choice”
Goto start:
End if
Print “The result of your operation is “; Result
End
Output
Please supply me with two values ?5,6
What do you want to do with these values?
1.)Addition
2.)Subtraction
3.)Multiplication
4.)Division
Enter your choice? 3

13 QBASIC techniques for Beginners by Pravesh Koirala.


QBASIC fundamentals 10/12/2007 14

The result of your operation is 30

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.

*Using logical operators with the If statements


The following are the logical operators
And
Or
Not
There are other logical operators too but I don’t want to mention it here. If
you are interested then go search it yourself. All the logical operators function according to their
name. Consider this small example.
There are three friends A, B and C. One day there is a party invitation for A
but B and C are left out. But A insists B and C to come. He says, “B and C must come otherwise I
won’t come”. This is a good example of And operator. It also checks that all the conditions are true
or not. Even if one of the condition is false the whole condition becomes false.
Again another day, A is invited for another party but B and C are left out
(again!). But A refuses. He insists that either B or C must accompany him otherwise he is not going to
attend the party. This condition clarifies the OR concept. At least one of the condition must be true
otherwise the whole condition is false.
But one day, A and B have exchange of some hot words. They become
annoyed with each other. And again a party invitation arrives. This time C is not involved but both A
and B are called for the party. Now A says, “I won’t come if B is coming”. This is a perfect example of
Not operator. If the given condition is true then the overall condition becomes false and vice versa.

The following program should clarify the examples.


CLS
Start:
Input “Enter your age ”; Your_age
If your_age <=0 Or your_age >120 then
? “Do you think I am a fool?”
Goto start:
Else if your_age >0 AND your_age<18 then
? “You are still a baby”
Else if your_age =>18 AND your_age<60 then

14 QBASIC techniques for Beginners by Pravesh Koirala.


QBASIC fundamentals 10/12/2007 15

? “You are grown up”


Else
? “You are Old”
End if
End
Output
Enter your age ? 189
Do you think I am a fool?
Enter your age ? 0.5
Do you think I am a fool?
Enter you age ? 30
You are grown up

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”.

*Truth charts for logical Operators


Truth chart resembles the results of the logical operator with respect to the conditions.
You can find it anywhere in Internet or Course books. And since you already had some idea about it
above, so I need not mention it.

15 QBASIC techniques for Beginners by Pravesh Koirala.


QBASIC fundamentals 10/12/2007 16

*The Goto statement


Goto statement is also sufficiently defined by its name. It simply directs the translator to a specific
location. Consider this program
CLS
Goto A:
C:
Print 5
Goto En:
B:
Print 9
Goto C:
A:
Print 8
Goto b:
En:
End
Output
8
9
5
This program is pretty self explanatory. Consider how the translator is
directed to different locations and how the numbers are printed in different order etc.

*The Gosub and Return statement


Now you will be introduced about a new aspect of programming i.e. modular programming. We will
only deal about subroutines under it.
Imagine that you need to build a large program. In such
case, you can’t manage the whole program and it looks really messy. Also there is a greater
possibility of errors. So, you need to break your program into small parts called as Sub module or
Subroutines or Subprograms. Gosub statement is used for that very purpose. Gosub is somewhat
similar to Goto but there is a small difference. Graphically,
Gosub
Main Sub
Program Return routine

Main Goto statement


Program

As illustrated by the following figure, Gosub


connects a program with a subroutine and Return command causes the program execution to be

16 QBASIC techniques for Beginners by Pravesh Koirala.


QBASIC fundamentals 10/12/2007 17

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

17 QBASIC techniques for Beginners by Pravesh Koirala.


QBASIC fundamentals 10/12/2007 18

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!

*General process of loop


1) Take a variable first and initialize it (set the first value like 1)
2) Carry out the statements.
3) Increase the value of counter (variable).
4) Test whether the value of variable is less than desired no of loops or not. If it is greater then end
the loop. Else redirect it to step 2

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:-

For variable = Initial value To Final value [Step value]


Statements
Next [variable]
In this loop you take a variable and initialize it with an initial value. Then we
write statements inside the body of the loop. Then the value of variable is increased by the STEP
Value. If STEP value is not mentioned then by default computer assumes it to be +1. Now the
translator checks whether the value of the variable is less than or equal to the final value or not. If it
is less or equal then it loops to the statements below the For command else it terminates the loop
and proceed forward and executes other statements. E.G:-
CLS CLS CLS CLS
For I = 1 to 5 For I =1 to 5 Step 2 For I = 5 to 1 Step -1 For I = 1 to 8
Print I Print I Print I Print I;
Next I Next I Next Next ‘May or not
End End End End ‘..mention var name
Output Output Output Output
1 1 5 12345678
2 3 4
3 5 3
4 2
5 1

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

18 QBASIC techniques for Beginners by Pravesh Koirala.


QBASIC fundamentals 10/12/2007 19

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.

*Updating the value of variable in Loop


Looping is much useful to repeat a set of statements multiple times. And besides there is one more
useful point to it. You can just update the value of a variable according to your requirement.
Consider a series:-
1
11
111
1111
11111
If you’re asked to generate this pattern of numbers then how will you do it? Just
think about the formation and dependency of each term with its preceding term.
1 ‘Can be assumed as an initial value
11 ‘11 = 1*10+1 (dependent on preceding value i.e. 1)
111 ‘111=11*10 +1 (dependent on preceding value i.e. 11)
1111 ‘1111=111*10+1 (“” ”” ”” ”” ”” ”” ”” ”” ”” ”” ”” ”” ”” )
11111 ‘11111=1111*10 +1 (“” “” “” “” “” “” “” “” “” “” “” “” “)
In this series 10 and 1 are consistently multiplied and added. So these are
some sort of constants. But 1,11,111,1111 etc are each of the preceding term. So we can use them
in a For..Next loop to get the pattern. E.G.
CLS
Term = 1 ‘Initialize the first term of the pattern
For I = 1 to 5
Print Term
Term = Term * 10 + 1 ‘Continuously update the value of Term according to the requirement
Next I
End
Take a paper and note down the value of Term and the result obtained at each loop.
This will develop a greater concept in you. I did hope that you will be able to solve some of the
problems now. Try this out
2 ‘First value
5 ‘5=2*2 +1
11 ‘11=5*2 +1
23 ‘23=11*2+1
47 ‘47=23*2+1

Well if you did this then why not try another?


1
4
9
25
36

19 QBASIC techniques for Beginners by Pravesh Koirala.


QBASIC fundamentals 10/12/2007 20

.. up to 9 term

First do this and check whether it is right or not


Answer
CLS
Res = 1
For I = 1 to 9
Print Res ^ 2
Res = Res + 1
Next
End
Well If you did this correctly then good! You’re improving. But please take your time,
to consider this program for the same question.

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?

*Nesting For…Next Loop


Nesting a loop means to write a child loop inside a parent loop. E.g.
For I = 1 to 3
For J = 1 to 2
Print “Hey Baby!”
Next J
Next I
This small program is capable of printing “Hey Baby!” in the output screen 6 times.
In this program the I loop is executed 3 times and J loop is executed 2 times on each I loop. This
results in the execution of Print statement 6 times.

*Some interesting patterns generated by Nesting loops.


CLS
For I = 1 to 5
For J = 1 to I
Print J;
Next J
Print
Next I
End
Output
12345
1234
123
12
1

20 QBASIC techniques for Beginners by Pravesh Koirala.


QBASIC fundamentals 10/12/2007 21

Can you tell the output of this program?


CLS
For I = 1 to 5
For J = 1 to I
Print I;
Next j
Print
Next I
End

And can you write a program to generate this pattern?


55555
4444
333
22
1
These all depends on your creativity. Anyways try all these out and if you can’t then
pro_science108@yahoo.com ☺.

*The While Wend Loop


This loop is somewhat dissimilar to For loop. For loop is based on the value of the variable. You can
tell by its structure in the program that how many times is it going to loop. But While loop is totally
based on conditions. Its syntax is
While {condition is true}
Statements
Wend

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

21 QBASIC techniques for Beginners by Pravesh Koirala.


QBASIC fundamentals 10/12/2007 22

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.

*The INKEY$ command


Actually, inkey$ is not a loop but since it is generally used with an infinite loop, thus, we shall be
dealing it. The inkey$ returns the key which is being pressed. For example

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.

22 QBASIC techniques for Beginners by Pravesh Koirala.


QBASIC fundamentals 10/12/2007 23

Chapter-4 (Library Functions)


Functions simply mean the process that gives a result. Imagine that there is a big factory of shoes.
There somebody just inputs some raw materials like leather and wood and the result is finished high
quality boots. So simply functions takes some input and gives some output. We can store those
output in variables and use it in our programs. Functions are always in upper case and if your
function isn’t converted automatically in uppercase then you can guess that something is wrong with
your codes. Functions need to be given some inputs in an special pre-determined format called
syntax.

*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.

The SIN, COS and TAN Functions


Each of the following returns the respective ratio of the angle. But always keep in mind, the angle
must be in radian measure. E.G.
CLS
Angle%=30 ‘Set the angle value in a variable
Angle!=Angle%*3.1416/180 ‘Change it into radian and store in a floating point type var
Res_Sine = SIN(Angle!)
Res_Cos = COS(Angle!)
Res_Tan = TAN(Angle!)
Print res_sine, res_cos, res_Tan
End
Here, you input the angle value into sin, cos and tan function. It gave a value and we
stored that value in respective variables. As I said earlier, keep in mind that while giving the value of
the angle, you must give it in radian measure else your whole calculations can be wrong.

*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.

23 QBASIC techniques for Beginners by Pravesh Koirala.


QBASIC fundamentals 10/12/2007 24

*The Len Function


Len function is one of the most important and basic string manipulating functions. It deals with
string value but it always returns integer type. Len simply returns the length of the string value in
character. Consider this,

Print Len(“Pravesh”) ‘Gives 7


Print Len(“P”) ‘Gives 1
Print Len(“ p ”) ‘Gives 3. Remember, space is also counted

*The STR$ and VAL Function


Always keep in mind, the process of storage of integer and string type values is different from each
other (discussed earlier). Also the operation of string is also quite different in QBASIC.
A$ = “1” A=1
B$ = “1” B=1
Print A$ + B$ Print A+B
End End

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

24 QBASIC techniques for Beginners by Pravesh Koirala.


QBASIC fundamentals 10/12/2007 25

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

25 QBASIC techniques for Beginners by Pravesh Koirala.


QBASIC fundamentals 10/12/2007 26

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.

*Left$ and Right$ Function


Left$ and Right$ are nothing but just modified form of the ultimate Mid$. The syntax of Left$ is:-
Left$ (string value, length)
Left$ just returns the leftmost length characters of the string value.
Following are some of its examples.
Left$(“Pravesh”, 3) returns “Pra”
Left$(“He llo”,4) returns “He l”
Left$(“1234”,1) returns “1”
So easy, isn’t it? Left$ also can be combined in loop for string
patterns.

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)

Right$(“Pravesh”,3) returns “esh”


Right$(“1234”,2) returns “34”
Right$(“Namaste !”,2) returns “ !”

Well so write a program yourself to generate this pattern.


5
45
345
2345
12345
Hints: use right$ function with the string set of “12345”.

*Program to find reverse string


CLS
Input “Any string that you wish to change”;St$
For I = Len(St$) to 1 step -1 ‘If you don’t remember then recall for loop
Char$ = Mid$(st$,I,1)
Rev$ = Rev$ + Char$
Next I

26 QBASIC techniques for Beginners by Pravesh Koirala.


QBASIC fundamentals 10/12/2007 27

Print “The reverse string is”; Rev$


End
If you take input as “Right” then according to our program For loop will
occur Len(“Right”) times i.e. 5 times. But the value of I starts from 5 and gradually decrease to 1.
Now each time mid$ separates the last char of the string and adds it in another variable. In this way,
we can get our result i.e. “thgiR”. Can you guess the output when you input “45”?

*Asc and Chr Function


You must be familiar with ASCII. There is a code for every character. You can use these functions to
get the codes of equivalent character or vice versa.

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”.

Program to generate character for each individual ascii value.


CLS
For I = 1 to 200
? “Character represented by” ; I ; “is” ; Chr$ (I)
Next
End
This small program will show you the corresponding character for each ASCII code.

*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.

*LCASE$ and UCASE$


“a ram” and “A RAM” is not same in computer language. Its due to their cases. The first one is in
lower case and second one is in upper case. But you can change the case of any string as you like
using lcase$ and ucase$ function.
? Lcase$ “PraVEsj” returns “pravesj” ‘converts only upper cases to lower case
? Ucase$ “abCDef” returns “ABCDEF” ‘converts only lower cases to upper case

Implementation of these Functions


It is quite obvious that you would like to check name of a person in your program. But the problem is
he might enter his name as “Pravesh Koirala” or “Pravesh Koirala” or “PRAVESH KOIRALA”. This
might affect your program as you will compare the name with a preset value and due to cases the
result may be incorrect. So you can use LCase or UCase to either change the text to full upper case or
full lower case and then compare to your preset value. For E.G.
CLS
Input “Enter your name”;nam$
If lcase$(nam$) = “christiano ronaldo” then (alternatively, if ucase$(nam$) = “CHRISTIANO
RONALDO” then)

27 QBASIC techniques for Beginners by Pravesh Koirala.


QBASIC fundamentals 10/12/2007 28

? “Dude I love your game”


End if
End

*HEX$ And OCT$


If you don’t know about Hexadecimal and Octal value then just leave it! HEX$(number) and
OCT$(number) just returns the equivalent Hexadecimal and Octal value of the number.
? HEX$(123) gives “7B”
?OCT$(123) gives “173”

*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

RND And RANDOMIZE


Randomization is a very method to implement in a guessing program. RANDOMIZE (number) is used
to start the randomize counter. After initialization, you can ask computer to generate a random

28 QBASIC techniques for Beginners by Pravesh Koirala.


QBASIC fundamentals 10/12/2007 29

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)

If MyGuess% = number then


? “Wow! You got that, Einstein”
Else
? “Good Try but sorry”
? “My guess was”;MyGuess%
? “But You entered”;number
End if
End
Randomization techniques can be really useful while making Games and
others. Can you make a program that will decide who won the lottery provided that lottery from
number 345 to 907 were sold. Try it!

User defined Functions


These functions are those functions that are defined by user only. But it is an advanced topic and it
will be covered under another volume of this book. But you need not wait for it. You can search in
internet. There are thousands of other books too!!!

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

29 QBASIC techniques for Beginners by Pravesh Koirala.

You might also like