Top 3 Products & Services
1. 2. 3. |
Dated: Aug. 12, 2004
Related Categories
BASIC Programming- Introduction
- History
- Lets the Game Begin
- Your First Program
- Variable in Qbasic
- More Advance Data Manipulation
- User Defined Type
- Subroutines and Functions
- Parameters
- Fucntions
- Reading and Writing to Files
- Displaying Graphics
- Designing Application in Qbasic
- Conclusion
Introduction:
QBasic is a very simple language to pick up, and yet it can accomplish a great deal. Granted you will probably never write Doom or Word Perfect with QBasic, but it has its strong points. One of them is to introduce people to programming without having to worry about the internal workings of the computer. It's simple to create games, business applications, simple databases, and graphics. The best aspect of the language is its close resemblance to English.
In the early days of programming, it was usually the scientific elite doing the programming, and they were usually trained above the average person to do their programming work. It was not until 1964 at Dartsmouth college that the Beginner's All-purpose Symbolic Instruction Code would be introduced -- more commonly known as BASIC. Using common English to perform processor tasks, BASIC became quickly popular, although it was disliked by programmers of more "low-level" languages such as assembly and FORTRAN. In 1985 Microsoft released a version of BASIC called QBasic with its MS-DOS 5.0 operating system. Since then, nearly every PC user has owned their own copy of QBasic, making it a widely known language.
History
QuickBASIC is an easier to use version of the original BASIC. BASIC stands for Beginners All purpose Symbolic Instruction Code. When it was first made, it was used on mainframes. But later, the language was widely accepted as their first computer language because of its easy-to-understand code. Back then, all languages were hard to understand because of their abstraction. Although BASIC is a good language for beginners, it is not a recommended language for a person who wants to become a professional programmer. The reason is it is not structural, that means it's easy to write codes that is hard to understand and follow. A recommended language for beginners is Pascal. I started with BASIC, I didn't have much problem with understanding my own big programs. I believe it is because I made my programs using structural method. So if you don't like Pascal, you can just learn BASIC and structural programming.
Lets the Game Begin
QBasic is very easy to use. Almost every single computer has it included with it. If you don't already know where QBasic is located on your computer, check the \DOS directory, or use a program to find QBASIC.EXE.
Note (Dec. 16, 2012): This tutorial was written when dinosaurs roamed about. If you're working with Windows based computer, you'll have to download .
To start using QBasic, load it up from the DOS prompt, and it should look something like the DOS editor. I know you'd like to get started right away, so I'll cut to the chase. Here's a sample program for you to type in:
Your First Program
--begin program--------------- CLS PRINT"Hello!" PRINT PRINT"This is my first program!" --end program----------------- CLS
This is just a list of commands that the computer will interpret and execute. Go up to the "RUN" menu and click "START". The scren will clear, and look something like this, with a "Press any key to continue" on the bottom of the screen.
Hello! This is my first program!
Notice it doesn't say CLS, or PRINT, or anything. It does give you a "Press any key to continue" message, but that's just QBasic's way of telling you it's done with it's work.
To begin with the explanation, the command 'CLS' stands for CLear Screen, and PRINT is quite self-explanatory. Just make sure that when you're PRINTing, have quotes on each side of what you want the screen to display. Fool around with the two commands until you get used to them. People who are already familiar with the menus at the top of the screen (and their function) can skip the next paragraph.
To begin a new program, go to the "FILE" menu and click "NEW." BEWARE - any program in memory will be LOST FOREVER if it is not saved. If you want to save a program, go to the "FILE" menu and click "SAVE." QBasic will prompt you for a file name, and your program will be saved to disk. If you want to load that program again, go to the "FILE" menu and click "LOAD". You will get a dialog of what QBasic files are in your directory. Double-click on the one you want to load.
Variables in QBasic
The Scripting Component contains the scripting languages used to create server-side processing scripts along with other objects through which the server's directory and file structures are accessed.
A variable, simply defined, is a name which can contain a value. Programming involves giving values to these names and presenting them in some form to the user. A variable has a type that is defined by the kind of value it holds. If the variable holds a number, it may be of integer, floating decimal, long integer, or imaginary. If the variable holds symbols or text, it may be a character variable or a string variable. These are terms you will become accustomed to as you continue programming.
Here are some examples of values a variable might contain:
STRING "hello, this is a string" INTEGER 5 LONG 92883 SINGLE 39.2932 DOUBLE 983288.18
The first is a string. Strings contain text. The last four are number types. But the computer does not know what kind of value you are trying to give a variable unless you tell it! There are two methods of telling the computer what kind of variable you are using:
- Explicitly declare the variable AS a type. This is done by using the DIM statement. Say you wanted to make a variable called number which would contain an integer (whole number, no digits after the decimal point). You would do it like this:
DIM number AS INTEGER
Then you would use that variable as an integer. The word DIM actually originates from the word Dimension. - Put a symbol after the variable name which is defined as representing that type. QBasic has a set of symbols which represent each variable type:
$ String % Integer & Long ! Single # Double
Appending one of these symbols to the name of a variable when you use it in the program tells the computer that you are using it as that type. This topic of data types is actually a difficult concept to grasp for newcomers to programming. The most common error in QBasic is the infamous Type Mismatch, which you will probably see a lot. This means that you are trying to put a value into a variable of the wrong type. You might be trying to put the letters "hi there" into an integer variable. If you don't define the type of the variable, then QBasic assumes it is of the Single type, which can often yield unexpected results. I prefer to use the type symbols after variable names, but some explicitly declare them usually at the head of their programs.
More Advanced Data Manipulation
There are numerous methods to manipulate data and present it to the user in QBasic. One is called an array. An array is a variable which can contain more than one value. For example, you might have an array called a, and you could assign data to the members of that array. There might be a value for a(1), and a different value for a(6). Before an array can be used, it must be declared. Arrays are declared with the DIM statement used in section 1. Here is an example of an array declaration:
DIM a(1 TO 100) AS INTEGER
There are now 100 different values that can be assigned to the array a, and they must all be integers. It could also look like this
DIM a%(1 TO 100)
Using the symbol % for integer. We call the different values for the array members of the array. Array a has 100 members. Array members can be assigned values by using a subscript number within parentheses after the array name, like this
a%(1) = 10 a%(2) = 29 a%(3) = 39
And so on. Now you're probably wondering why the statement for declare is DIM. This comes from a term used in earlier programming languages that means dimension. That still doesn't answer the question... why not use the statement DECLARE? Well, an array can have more than one dimension. Arrays with multiple dimensions have y members in the second dimension for every x member of the first dimension in the following algorithm:
DIM array( 1 TO x, 1 TO y) AS INTEGER
So if the actual declaration looked like this:
DIM a$( 1 TO 3, 1 TO 3
You would have the following members to assign values to:
a$(1,1) a$(1,2) a$(1,3) a$(2,1) a$(2,2) a$(2,3) a$(3,1) a$(3,2) a$(3,3)
A two dimensional array is useful for tracking the status of each piece in a checkers game, or something of the like. Recall the last example program of section that we had a program that would ask the user for the item name, the item cost, and the quantity of that item, the spit out the data just given in a nice format with the total in the right hand column. Well, with only one item, this program isn't very practical. But now with our newfound knowledge of arrays and the knowledge we already have of loops, we can create a somewhat useful application. The process will start with the program prompting the user for the number of items that will be calculated. Then the program loops for the number of times that the user entered at the beginning, assigning the data entered into a member of an array we will declare.
User Defined Type
Now on to a new topic: User defined types. Recall that a type is the type of value a variable can have, such as integer, string, long, double, or single. You can create your own types which contain one or more of the already defined types. Here is an example of a user defined type:
TYPE employeeType firstname AS STRING * 30 lastname AS STRING * 30 age AS INTEGER wage AS SINGLE END TYPE
We have defined a new type, which consists of four data members, as I call them. We can now declare a variable of this type:
DIM employee AS employeeType
A variable of a user defined type is like an array, in that it can have more than one value assigned to it. But you can have an array of a variable of a user defined type as well, so things can get rather complex. Anyway, now that you have a user defined type, you can assign values to the data members of that variable. Use a period to access a data member of a type, like this:
employee.firstname = "Bob" employee.lastname = "Foster" employee.age = 24 employee.wage = 6.78 This could have been helpful in the last program we made with the top 10 list. We could have declared a user defined type called playerType, like this: TYPE playerType name AS STRING * 20 score AS INTEGER END TYPE
and then declared an array of variables of that type
DIM player(1 TO 10) AS playerType
That would have made our code more efficient, but not necessarily more readable. Notice when we declare a string in a user defined type that it seems as if we are multiplying it by a number. Actually, we the number after the * defines the maximum length of the string. You must define this because the size of a user defined type must be known by the computer. Any value assigned to this string data member which exceeds the length specified is truncated.
User defined types can serve more than to be efficient. They are the heart of the random access file mode, which is commonly used in database files. A database is a method of organizing large quantities of information in records and fields. In a record, there are a set of fields which are constant in every record. A field's value changes from record to record, however. Just the name of the field remains constant. So how does this relate to user defined types? Well think of a variable of a user defined type as a record in the database, and the data members fields of the records. Employee may be a record, and firstname, lastname, age, and wage may be fields. Values can be assigned to the fields in each record, thus constructing a database. A file opened for random access is organized in this fashion, with records split into fields. Each record in the random access file is given a record number which can be convenient in a database environment. In the OPEN statement for opening a random access file there is one extra argument. We must specify the length in bytes of how much space one record will occupy -- the record length. This can be easily taken by taking the LENgth of a variable defined as the user defined type we are going to use. So back to our employee example, we could use the LEN function to get the size in bytes of the employee variable, which is an employeeType. Here's the code:
recordLen# = LEN(employee) OPEN "database.dat" FOR RANDOM AS #
:LEN = recordLen# LEN stands for length. You can also use the LEN function to get the number of characters in a string, but that is kind of irrelevant right now. So let's construct a simple database that will keep track of the employees of a business.
' Section 1
CLS TYPE employee Type firstname AS STRING * 30 lastname AS STRING * 30 age AS INTEGER wage AS SINGLE END TYPE DIM employee AS employeeType
' Section 2
PRINT "1.) Create new recordset" PRINT "2.) View existing recordset" INPUT "Which option? ", selection% '
Section 3
IF selection% = 1 THEN INPUT "How many employees are in the company? ", numRecords% recordLen# = LEN(employee) OPEN "database.dat" FOR RANDOM AS #1 LEN = recordLen# FOR i% = 1 TO numRecords% CLS< INPUT "First name: ", employee.firstname INPUT "Last name: ", employee.lastname INPUT "Age: ", employee.age INPUT "Wage: ", employee.wage PUT #1, ,employee NEXT i% CLS CLOSE #1 PRINT "Recordset creation complete" END END IF
' Section 4
IF selection% = 2 THEN recordLen# = LEN(employee) OPEN "database.dat" FOR RANDOM AS #1 LEN = recordLen# format$ = "\ \,\ \ ### $$##.##" PRINT "Last name First name Age Wage " PRINT "------------------ ------------------ --- -------" DO WHILE NOT EOF(1) GET #1, ,employee 'Sorry about the length of this line!!! PRINT USING format$; employee.lastname; employee.firstname; employee.age; employee.wage LOOP CLOSE #1 END END IF
I've split this program into sections again because that seems to work well for the larger ones.
Section 1: We're defining the user defined type and declaring a variable of that type.
Section 2: The first thing the user sees is a menu with the option to either create a new database (recordset) or view the existing one. The user is prompted to make a selection which is stored in the variable selection%.
Section 3: If the user chose option 1 -- create a new recordset -- then this code is executed. First we prompt the user for how many employees are in the company so we know how many times to go through a loop. Then we open the file, prompt the user for the data for each variable, and write the whole record to file. The record is written using the PUT statement. The first argument in PUT is the file number, the second is the record number, and the third is the data to be written to file. If no record number is specified for the second argument, the current file position is used, which will just append what we specify after what is already there. This works fine, so we don't need to worry about explicit record numbers. Notice that we are writing the whole employee variable to file. This is because we write records to file, and the whole variable contains the data for the data members (fields).
Section 4: If the user chooses to view the existing recordset, then we first open the file, define a format string for the printout, and print the headers. Next we have a loop until the end of file is encountered. Notice the GET statement, which is used to read from a random access file. The first argument is the file number we want to read from, the second is the record number (which we are leaving blank because we can read from the current position [CP] like we did in the PUT statement), and the third is the variable in which we read the data in to. This variable must be of the same type that we wrote with or else the types will be incompatible. You'd probably get a TYPE MISMATCH error if a different variable is used because the fields are not equal, so the program does not know what to assign the data to.
Well that's it for random access. You should now have a good knowledge of what QBasic is about.
Subroutines and functions
A subroutine (also called a "module") is a "mini-program" inside your program. In other words, it is a collection of commands--and can be executed anywhere in your program.
To create a subroutine:
Go to the "Edit" menu Select "New Sub" Enter a name for the subroutine Type a list of commands between SUB and END SUB
To use the subroutine: Press F2 Select "Untitled" Press Enter to return to the "main module" Use CALL to execute the subroutine.
Parameters
Parameters are numbers and strings that you pass to a subroutine, much like a QBasic command
This passes 16 as a parameter:
CALL OutputNumber(16)
' Notice the parentheses around the parameter "num." ' Any variables placed inside the parentheses are set as ' the subroutine's parameters.
SUB OutputNumber (num) PRINT num END SUB Output: 16
Functions
Function is the same as a subroutine, except it returns a value. Also, you must leave out the CALL command. To return a value, set a variable with the same name as the function.
PRINT Add(10, 7 ) FUNCTION Add (num1, num2) Add = num1 + num2 END FUNCTION Output: 17
Since a function can return a value, the name of the function can end with special characters.
Reading and Writing to FIles
To save data to a file:
Call the OPEN command, specifying the file name, file mode (OUTPUT), and file number. Use PRINT, followed by the file number and the data you want to write. Close the file using the CLOSE command.
The following opens a file, using mode OUTPUT and number 1, and then saves the text Hello World! to the file:
OPEN "testfile.dat" FOR OUTPUT AS #1 PRINT #1, "Hello World!" CLOSE #1
To open a file for "reading," call OPEN and pass INPUT as the file mode. Then you can read the data by using the INPUT command.
OPEN "testfile.dat" FOR INPUT AS #1 INPUT #1, text$ CLOSE #1 PRINT text$ Output: Hello World!
Displaying Graphics
Before you can show graphics images on the screen, you must call the SCREEN command. SCREEN sets the graphics mode.The following program uses graphics mode 13 (320x200) to display a line, then returns back to text mode:
SCREEN 13 ' This starts at 10 pixels from the left, 10 from ' the top and goes to point (100, 100): LINE (10, 10)-(100, 100) WHILE INKEY$ = "": WEND ' Waits until a key is pressed SCREEN 0 ' Returns to text mode
You can also draw a colored line.
SCREEN 13 LINE (10, 10)-(100, 100), 192 ' Dark green WHILE INKEY$ = "": WEND SCREEN 0
To draw a single pixel, use PSET.
SCREEN 13 PSET (160, 100) WHILE INKEY$ = "": WEND SCREEN 0
The following displays a circle at (160, 100) with a radius of 50:
SCREEN 13 CIRCLE (160, 100), 50 WHILE INKEY$ = "": WEND SCREEN 0
Finally, to display a square, use:
LINE. SCREEN 13 LINE (10, 10)-(100, 100), 192, B ' Notice the B WHILE INKEY$ = "": WEND SCREEN 0
Designing Appliations in Qbasic
It is not practical in real world terms to set up an application in one long list of code. Many early programming languages were purely linear, meaning that they started from one point on a list of code, and ended at another point. All of the code I have written in this tutorial so far has been purely linear. However, linear programming is not practical in a team environment. If one person could write one aspect of code, and another write another part of the program, things would be much more organized. QBasic contains the capability to meet these needs, called modular programming. You can break a program into different "modules" which are separate from the main program and yet can be accessed by any part of it. I highly recommend the use of separate modules in programming applications, although it is not a simple task to learn.
These separate modules are also known as procedures in the QBasic environment. There are two types of procedures: subs and functions. Subs merely execute a task and return to the main program, which functions execute a task and return a value to the main program. An example of a sub might be a procedure which displays a title screen on the screen, while a function may be a procedure that returns a degree in degrees given a number in radians. Function procedures are also used in Calculus, so you Calculus people should already be familiar with functions.
Programming takes knowledge of the language and a creative mind... programs are made by programmers with both. If you can develop a creative mind, then you can develop any program conceivable.
Conclusion
QBasic is a fun and widespread language. BASIC is an extremely popular language with thousands of different versions world-wide, so it is mandatory that you learn it. But if you will continue in programming, knowing a Mid-level DOS language will not suffice in the real world. I suggest learn ing some Pascal next, and then moving on to the world of Windows. When I say "learn" I do not mean memorize every command in the language, I mean "get familiar with the concepts." You may not learn how to do anything beyond what you can do in QBasic, but that's fine. Back To Top
Now that you've gotten free know-how on this topic, try to grow your skills even faster with online video training. Then finally, put these skills to the test and make a name for yourself by offering these skills to others by becoming a freelancer. There are literally 2000+ new projects that are posted every single freakin' day, no lie!
Previous Article | Next Article |
thank you manas. we old folks love it from our school times.
PS : We need your support and suggestion please read this article "We need your help
I'm not a qBasic person myself. But I'm a tech geek. And I can assure you, we dont attract females due to our prowess on any technology, unless the female is a geek herself. But from personal experience, the only tip I can give you....
And I mean that in a very seriously...."Just don't care about attracting and you'll be wanted more".