qbasic

38
Chapter 1: Introduction to BASIC Programming Have you ever, when seeing a game or another program, asked yourself : How did they do that? Every program, every game you run on your computer, has been written by someone using a special software development tool called a programming language. By definition: A program is a set of instructions that makes the computer work. The instructions constitute of keywords, sometimes called reserved words, that have special functions such as: Clearing the screen Writing data to the screen Getting user input Executing loops Changing colours Playing sounds Opening files Etc. There are different programming languages. Some are difficult to use, understand, other are limited to special purposes such as scientific calculations, drawing or database management. Some programming languages out there: Programming language Purpose Difficulty C/C++ General Difficult Pascal Educative Medium Logo Drawing, for Children Very Easy COBOL Business ??

Transcript of qbasic

Page 1: qbasic

Chapter 1: Introduction to BASIC

ProgrammingHave you ever, when seeing a game or another program, asked yourself : How did they do that? 

Every program, every game you run on your computer, has been written by someone using a special software development tool called a programming language.

By definition:    A program is a set of instructions that makes the computer work.  The instructions constitute of keywords, sometimes called reserved words, that have special functions such as:

Clearing the screen Writing data to the screen Getting user input Executing loops Changing colours Playing sounds Opening files Etc.

There are different programming languages. Some are difficult to use, understand, other are limited to special purposes such as scientific calculations, drawing or database management.

Some programming languages out there:

Programming language Purpose Difficulty

C/C++ General Difficult

Pascal Educative Medium

Logo Drawing, for Children Very Easy

COBOL Business ??

FORTRAN Scientific ??

BASIC General  Easy 

Page 2: qbasic

The BASIC programming languageBASIC is a high level language that was developed in 1964 by John Kemeney and Thomas Kurtz at the Dartmouth College in the USA.

It is one of the most popular programming language because it easy to learn and use. It was meant to be as easy as possible. 

BASIC is an acronym for:

Beginner's All - Purpose Symbolic Instruction Code

Different Versions of BASIC

There are different versions of BASIC. Among them:

GW-BASIC, Turbo BASIC, Quick BASIC, Qbasic, Visual Basic, Liberty BASIC, Power BASIC, etc. 

Visual Basic is probably the most popular and powerful of all. It has many advanced features which allow you to write great programs in a short time with a minimum of code and sometimes no code at all from your part if you're to use the application wizard. However it would be, IMHO, wiser and easier to start with a more standard version of BASIC like QBasic.Though there are different versions of BASIC, most of the instructions are the same.

Programming in Qbasic

Qbasic was developed in 1987. It is a light version of Quick BASIC. It contains about 250 reserved words.

Where is Qbasic?

Qbasic comes with Ms-DOS 5.0. It is also available on your Windows 95/98 Cd-Rom.

How to load Qbasic?

The executable for Qbasic is Qbasic.exe. If Qbasic is in your path you can, from the DOS prompt, type:

  C:\>Qbasic 

If you have Windows installed and have Qbasic on you hard disk, the easiest would be to put a shortcut  on your desktop or in your start menu programs. Get the help of a computer guru if necessary.

Page 3: qbasic

The Qbasic IDE

The Qbasic IDE

The Qbasic IDE is quite simple to understand. It is divided into two windows: the Untitled Window and the Immediate window. 

You should type your instructions in the untitled window.

To run your program, click on  Run -> Start  or  Press F5

To get out of Qbasic, click on  File -> Exit.

We'll see more about the Qbasic IDE later.

Two BASIC reserved words

It is not necessary for you to know all the BASIC reserved words to get started. You could write a lot of  programs using about 10 keywords. To get started we'll be using only two of them:

CLS This statement is used to clear the screen.

PRINT The PRINT statement is used to display data on the screen.

 Your First BASIC program

To begin we will write a simple program that will output a text on the screen.Type the following in the untitled window:PRINT "Hello!"

Page 4: qbasic

PRINT "This is my first BASIC program."

To run your program:

Click on Run  Start

or

Press the function key F5

The output on the screen will be as follows:Hello!This is my first program.

 

 

 

 

 

 

 

Press any key to continueOnce the execution of your program is completed, BASIC will display a "Press any key to continue" message on the screen. So press any key to return to your programming environment.If you run your program many times, you will notice that the same text will be displayed several times on the screen as shown below:Hello!This is my first program.Hello!This is my first program.Hello!This is my first program.Hello!This is my first program.

 

Page 5: qbasic

 

 

 

Press any key to continueTo get your screen cleared each time you run you program, put the CLS statement at the beginning of your program:CLSPRINT "Hello!"PRINT "This is my first BASIC program."

Note the presence of inverted commas(" ") in the PRINT statement. Always put inverted commas if you want to output sentences or characters. We will be discussing more about it in Chapter 3.[ Previous Index Next ]

Mathematics symbols

Some mathematical operators and their BASIC equivalent:

Operation Mathematics BASIC equivalent

Plus + +

Minus - -

Multiply x *

Divide /

Exponential a2 a^2

Page 6: qbasic

Qbasic Tutorial: Chapter 2

Storing data in the computer memoryData types: Constants and Variables

You may need to store data in the computer when writing your program.

Data is classified into 2 types:

Numbers Character Strings

Example of numbers:

10    +5    0.32    -1.234

Examples of character strings:

"Hello! how are you?"   "John Smith"   "14 Royal Road"   "$123"

Characters consist of letters, numbers, symbols and special characters.

To store data in the memory you will need to put them first in memory variables or constants. 

A memory variable will store values that vary, change.A memory constant will store values that remain constant (i.e. they don't change).

The Computer Memory

The memory of the human being contains millions of cells that store the different information that you have acquired in your life. Similarly the computer memory could be represented as storage cells. Each cell can be given a name or an address as follows:

Value 10 +5 0.32 -1.234

name of cell a b c d

 

Value Hello! How are you John Smith 14 Royal Road $123

Page 7: qbasic

name of cell a$ b$ c$ d$

How to use the memory in BASIC?

Remember! Data are store in memory variables or constants. In Qbasic variables should respect the following rules:

The length should not be greater than 40 characters They should start with a letter They should not contain spaces They do not support certain characters such as (

If you don't put a suffix, BASIC considers the variable as being of single-precision type

The table below shows the different types of variables:

Data Types Suffix

Single-precision !

Integer %

Double-precision #

Long-integer &

String $

The first 4 types are used to store numbers. o The Single-precision & double-precision types store floating numbers.o The integer & long-integer types store integers (numbers without 

decimal points). The String variables store characters, letters, texts, sentences.

Examples:

Code Remark

a% = 10 Assigns the value 10 to variable a%.

Page 8: qbasic

message$ = "Hello friend" Stores the text "Hello friend" in the memory variable message$.

number1 = 10number2 = 15sum = number1 + number2

Assigns 10 to variable number1.Assigns 15 to variable number2.Assigns 25 to variable sum.

b% = 4.5 In this case BASIC will truncate the decimal part of the number and store only 4 in the memory. Note:- Though this is a mistake, BASIC won't generate an error message. 

c! = 10.123 Single-precision variables are used to store floating points.

c = 10.123

 

Same as above. When a variable has no suffix, it is considered as being a single-precision variable.

 

Declaring variables

BASIC has received many critics because of its ability of creating & declaring variables on the fly. Qbasic allow you to declare variables.

The DIM statement is used to specify a data type for a variable. Variables declared should not end with a suffix.

The syntax is as follows:

DIM variable AS type

Example:

 

DIM userrname AS STRINGDIM age AS INTEGERusername = "John Smith"

Page 9: qbasic

age = 23

The code above is equivalent to

username$ = "John Smith"age% = 23

So what method of working with variables is better? 

Personally, though you might encounter both ways in the tutorial, I prefer to use the first one. It's a good habit to declare every variable you use.

BUGS caused by Misspelled variables

One of the most common bugs in BASIC programming is misspelled variable names. I often encountered the following mistakes while teaching BASIC to beginners:

 

length = 10Breadth = 5area = lenght * breadth PRINT area

The variable "length" is wrongly spelled in the 3rd line. BASIC differentiates between "length" and "lenght". It will look for the value of variable "lenght" in the memory. Since it could not find it, BASIC will assign 0 to the variable. 

So when you print the contents of variable "area", you will get a 0 instead of 50.

Unfortunately, apart from checking whether your variable was correctly written, we can't do much to prevent these types of mistakes. However if you are working in VBDOS, use the  OPTION EXPLICIT  statement to force all variables to be declared. The program will tell you that variable "lenght" has not been declared, giving you the opportunity to correct your mistake.

The PRINT statement - Writing data to the screen

The print statement is used to write data on the screen.

You can write:

Numbers

Page 10: qbasic

Characters, Sentences, Texts The contents of memory variables and constants

Note: Characters and sentences are written within inverted commas(" "). What is written within inverted commas is displayed as is during run time.

The following examples illustrate the different ways to use the PRINT statement:

Code Screen Output Comment

PRINT "5" 5 Writing character 5 to the screen.

 

PRINT 5  5 Writing number 5 to the screen.

 

PRINT 5PRINT "5"

 55

 

Note the space before the number 5 in the first line. BASIC always puts a space for +/- signs when printing a number.

PRINT "5 + 7" 5 + 7

 

What is within inverted commas is written as is.

PRINT 5 + 7  12

 

Writing the sum of 5 and 7 to the screen

PRINT 6 * 7  42

 

The * sign is used for multiplication.

PRINT 12 / 4  3

 

The / sign is used for division.

PRINT 8 - 3  5

 

 

a = 3b = 4c = a + bd = a * b

 3 4 7

a, b, c and d are memory variables. The value 3 is assigned to memory variable a.The value 4 is assigned to memory 

Page 11: qbasic

PRINT aPRINT bPRINT cPRINT d

 

 12 variable b.In the 3rd line, the computer looks assigns the sum of memory variables a and b to memory variable c.In the 4th line the computer looks assigns the product of memory variables a and b to memory variable d.In line 5, the computer looks for the value of memory variable aand writes it to the screen.

a = 3PRINT "a"

 

a Did you expect to get 3 on the screen? Don't forget that whatever is within inverted commas is written as is.

The correct code should be:

a = 3PRINT a

We will see more features of the PRINT statement later.

Qbasic Tutorial: Chapter 4

Solving Mathematical Problems (Part 1)

Solving simple mathematical problems is one of the easiest tasks that you could do in BASIC. If you are more keen at writing a game or making graphics, you will have to be patient.:) We'll deal about that later.

Before proceeding, you'll have to understand some Basic concepts:

What is a program?

A program is a set of instructions that makes the computer work.

In most programs you will have to write you will have to think as follows:

What data do I need to give to the computer? What operations will the computer have to perform with the data given? What results will the program display

Page 12: qbasic

There are three parts in every task that we accomplish 

Input Process Output

Input: What is needed

Process: What you need to do, calculate with the input

Output: The result obtained when the process has been done

 Before beginning to code your program, it is important to write algorithms or pseudo codes in plain English that will outline what you want to do. 

Algorithms

 An algorithm is a set of precise instructions for solving a problem.  Algorithms can be represented in plain English or in form of flowcharts

Here's a simple algorithm for calculating the sum of 2 numbers

Get the first numberGet the second numberCalculate the sumDisplay the sum

Let's illustrate this concept using some mathematical examples:

We'll be using colours to differentiate between the Input, Process and Output parts of the algorithm and program code.

Example 1: Finding the sum of 2 numbersWrite a program that will display the sum of numbers 8 and 12

Algorithm Program Code

Get the first numberGet the second numberCalculate the sumWrite down the result

number1 = 8number2 = 12sum = Number1 + Number2PRINT sum

Output on Screen20  

Page 13: qbasic

   

You will have noticed that this program is not very explicit. The following code makes the presentation more understandable as follows

Enhanced Example 1: Finding the sum of 2 numbers

Program Code

CLSnumber1 = 8number2 = 12sum = Number1 + Number2PRINT "This program finds the sum of two numbers"PRINT "The first number is:"PRINT number1PRINT "The second number is:"PRINT number2PRINT "The sum is:"PRINT sum

Output on ScreenThis program finds the sum of two numbers"The first number is:8The second number is:12The sum is:20     

The use of semi-colons in the PRINT statement tells BASIC to keep the cursor on the same line.

More Enhancement to Example 1: Finding the sum of 2 numbers

Program Code

CLSnumber1 = 8

Page 14: qbasic

number2 = 12sum = Number1 + Number2PRINT "This program finds the sum of two numbers"PRINT "The first number is:";PRINT number1PRINT "The second number is:";PRINT number2PRINT "The sum is:";PRINT sum

Output on ScreenThis program finds the sum of two numbers"The first number is: 8The second number is: 12The sum is: 20     

 Solving Mathematical Problems (Part 2)

As we say:   Practice makes perfect.  Here are more examples:

Example 2Write a program that will display the product of numbers 8 and 12

Algorithm Program Code

Get the first numberGet the second numberCalculate the sumWrite down the result

number1 = 8number2 = 12sum = Number1 + Number2PRINT sum

Be careful about not naming variables after BASIC reserved words. In the example below, you might be tempted to use the word "base" for to store the base of the triangle. The word "BASE" cannot be used. It is a reserved word in BASIC

Example 3Write a program that will calculate the area of a triangle of base = 10 and height = 5

Algorithm Program Code

Get the baseGet the heightCalculate the area

'The word BASE is reserved in BASIC'So we'll use variable tbase to store the basetbase = 10

Page 15: qbasic

Write down the area height = 5area = 1/2 * tbase * heightPRINT area

As it is the case in mathematics, operations in BASIC follows the BODMAS (Bracket, Of, Division, Multiplication, Addition, Subtraction) sequence. In the example below, BASIC will calculate the sum of the length and breadth within brackets then multiply it by 2.

Example 4Write a program that will calculate the perimeter of rectangle of Length = 20 and breadth = 8.

Algorithm Program Code

Get the lengthGet the breadthCalculate the areaWrite down the area

length = 20breadth = 8area = 2 * (length + breadth)PRINT area

There may be several ways to process a task in BASIC. Use the one that suits you better.

Example 5 (method 1)Write a program that will calculate the area of a circle of radius = 7.

Algorithm Program Code

Get radiusGet piCalculate the areaWrite down the area

radius = 7pi = 22/7area = pi * radius * radiusPRINT area

 

Example 5 (method 2)Write a program that will calculate the area of a circle of radius = 7.

Algorithm Program Code

Get radiusGet piCalculate the areaWrite down the area

radius = 7pi = 22/7area = pi * (radius ^ 2)PRINT area

Page 16: qbasic

Enhancing Program Presentation

It's important for you to enhance you program by:

Documenting your program Using meaningful variables Saying what is the purpose of the program

Documenting your program

As you will notice later, programs may become huge, thus difficult to understand. The REM statement allows you to put remarks in your program. 

Any line starting with the REM statement is ignored at run-time.

You can replace the REM statement by a single-quote ( ' ) symbol.

The two lines below are similar:

REM Program written by H.B.' Program written by H.B.

The single-quote form of REM can also be placed at the end of a line

PRINT "Welcome everybody" 'Welcome message

Using meaningful variables

The use single-letter variables may be easy to type especially if your typewriting speed is slow. However they may cause your program to be difficult to understand in the long-run. The use of meaningful variables makes your program easier to understand and maintain. 

Here is an illustration:

x = 2000y = 10z = x * (100 + y)/100

Could you guess the code above? Now see how it is easy when meaningful variables are used:

Page 17: qbasic

OldSalary = 2000PercentageIncrease = 10NewSalary  = OldSalary  * (100 + PercentageIncrease )/100

Saying what is the purpose of the program

Many novice programmers or children learning how to program, often neglect to say what is the purpose of their program. 

Example of an undocumented program:

a = 20b = 30c = a * bPRINT "The product is "; c

As we said above, use the REM statement to put remarks, use meaningful variables and, at run-time, say what your program is doing.

REM This program calculates the product of 2 numbers: 20 and 30.number1 = 20number2 = 30product = number1 * number2PRINT "This program calculates the product of 2 numbers"PRINT "The first number is"; number1PRINT "The second number is"; number2PRINT "The product is "; product

 

Getting user input at run-time

Two commands or functions that allow you to get user input at run-time are:

The INPUT statement The INKEY$ function

The INPUT statement

The INPUT statement reads data from the user and stores it to a memory variable. The syntax is as follows:

Page 18: qbasic

INPUT [prompt] ; [variable]

or

INPUT [prompt] , [variable]

or

INPUT [variable]

Example:

Example 1: Asking the user for his nameFinding the sum of 2 numbers

Program Code

DIM yourname AS STRINGPRINT "Enter your name:";INPUT yournamePRINT "Hello"; yourname; ". Have a nice day!"

Output on ScreenEnter your name: LoulouHello Loulou. Have a nice day!   

The lines:

PRINT "Enter your name:";INPUT yourname

can also be written as:

INPUT "Enter your name:"; yourname

Personally I prefer to use the first option because it is easier to understand and because it is the standard procedure in most programming languages.

Example 2: Asking the user for his score in English and Math and calculating the sum

Program Code

Page 19: qbasic

DIM english AS INTEGERDIM math AS INTEGERDIM sum AS INTEGER PRINT "Enter your score in English:";INPUT englishPRINT "Enter your score in Math:";INPUT mathsum = english + mathPRINT "The sum is:"; sum

Output on ScreenEnter your score in English: 65Enter your score in Math: 59The sum is: 124  

 

Getting user data at run-time (continued)

The INKEY$ function

The INKEY$ function reads a character from the keyboard. Its main advantage over the INPUT statement is that it does not require the user to press the ENTER () key. It is thus more appropriate in games.

The program below displays a sentence repeatedly until the Escape (Esc) key is pressed. 

DO

    PRINT "Press the escape (Esc) key to stop!"

LOOP UNTIL INKEY$ = CHR$(27)

 

Example 1: Choosing between two optionsProgram Code

PRINT "1. Play Hangman"PRINT "2. Play Tetris"

Page 20: qbasic

PRINT "Enter your choice:"DO  a$ = INKEY$LOOP UNTIL a$ = "1" OR a$ = "2"IF a$ = "1" THEN  PRINT "You have chosen to play Hangman."END IFIF a$ = "2" THEN  PRINT "You have chosen to play Tetris."END IF

Output on ScreenIn the program test below the user has pressed number "1"

1. Play Hangman2. Play TetrisEnter your choice:You have chosen to play Hangman.  

The INKEY$ function is more appropriate in menu options and in games such as Hangman, Tetris and other games where continuous input has to be monitored. See also: A simple drawing program. 

Making Decisions

You may need to ask the user to choose between one or more options. The 

IF - THEN - ELSE statement and the SELECT CASE statement

are used to make decisions depending upon specified conditions.

The IF - THEN - ELSE statement

The syntax for the If then statement is as follows:

IF condition1 THEN[ List of instructions to be executed if condition1 is met]END IF

 

Page 21: qbasic

IF condition1 THEN[ List of instructions to be executed if condition1 is met ]ELSE[ List of instructions to be executed if condition1 is not met ]END IF

 

IF condition1 THEN[ Do what if to do condition1 is met ]ELSEIF condition2 THEN[ Do what if to do condition1 is not met and condition2 is met]ELSE[ Do what if neither condition1 nor condition2 are met ]END IF

 

Example: Telling whether you have passed the testWrite a program that will ask the user for his score in math and say whether he has passed the test. The pass mark is 40.

Algorithm Program Code

Clear the screenWrite message on screenGet user scoreCheck whether the score is greater than 40 and print "You have passed the test"

CLSPRINT "Enter your score in maths: ";INPUT scoreIF Score >= 40 THEN     PRINT "You have passed the test."END IF

Test 1: Output on ScreenEnter your score in maths: 45 You have passed the test.    

Test 2: Output on ScreenEnter your score in maths: 30     

Page 22: qbasic

You will have noticed that in test 2 the program did not display any message because the condition was not met. You can use the ELSE statement to give a message when a condition is not met. Here's an illustration:

Program Code

CLSPRINT "Enter your score in maths: ";INPUT scoreIF Score >= 40 THEN     PRINT "You have passed the test."ELSE    PRINT "You have failed the test."END IF

Test 1: Output on ScreenEnter your score in maths: 45 You have passed the test.    

Test 2: Output on ScreenEnter your score in maths: 30 You have failed the test.     

Sometimes you may need to use nested IF - THEN - ELSE statement ie and IF-THEN-ELSE statement inside another IF-THEN-ELSE statement.

 

Making Decisions (continued)

The SELECT CASE statement

The SELECT CASE statement is another way to make decisions in BASIC.

The syntax is as follows:

Page 23: qbasic

SELECT CASE testexpression    CASE expressionlist1        [statementblock-1]    CASE expressionlist2        [statementblock-2]]...    CASE ELSE        [statementblock-n]]END SELECT

Example

The example below illustrates how to use the select case statement

Algorithm Program Code

Display the menuGet user choiceSelect choice:   case choice = 1   Say "You have chosen to play Tetris"  case choice = 2   Say "You have chosen to play Hangman"  case choice = 3   Say "Goodbye"  case choice = 4   Say "Wrong choice"End select

 

'Designing menuPRINT "1. Play Tetris"PRINT "2. Play Hangman"PRINT "3. Exit"INPUT "Enter your choice"; choiceSELECT CASE choice  CASE 1     PRINT "You have chosen to play Tetris"  CASE 2     PRINT "You have chosen to play Hangman"  CASE 3     PRINT "Goodbye"     END  CASE ELSE     PRINT "wrong choice"END SELECT

Creating loops

A loop is used to repeat a block of statement a certain number of times until a condition is met. There are 4 ways to execute loops in BASIC. 

The FOR NEXT statement The DO LOOP statement

Page 24: qbasic

The WHILE WEND statement The GOTO statement

The most popular are the FOR NEXT and DO LOOP statements.

Where are they used? Here are some examples:

In solving mathematic problems where you have to print a list of numbers which are incremented steadily.

In games where you have to monitor continuously for keyboard input or mouse input

The FOR NEXT Statement

The FOR NEXT statement is used to repeat a block of instructions a specified number of times. The syntax is as follows:

FOR counter = start TO end [STEP increment]    [block of instructions]NEXT In the FOR NEXT statement a block of instructions is executed a number of times. The value of the variable counter is incremented by 1 until it equals to the value ofend. The variable counter, by default, increases by 1. You can change the rate at which the variable counter increments after each revolution by using the STEP parameter: See example 2 for an illustration.

Examples:

Example 1:This program print integers from 1 to 10Program Code Output

DIM counter AS INTEGERFOR counter = 1 TO 10   PRINT counterNEXT

1234567

Page 25: qbasic

8910

In the example above the instruction in green: PRINT counter is executed 10 times. After each loop the value of the variable counter is incremented by 1. 

Example 2:This program print odd numbers from 1 to 10Program Code Output

DIM counter AS INTEGERFOR counter = 1 TO 10 STEP 2   PRINT counterNEXT

13579

 

The DO LOOP statement

The DO - LOOP statement executes a block of instructions while or until a condition is true.

The syntax is:

DO    [List of instructions]LOOP UNTIL condition is met or DO    [List of instructions]LOOP WHILE condition is met While a counter is automatically incremented in the FOR - NEXT statement, you will have to increment the counter yourself with the DO - LOOP statement.Below is a comparison of the two methods: 

Page 26: qbasic

The two codes below are equivalent

FOR - NEXT DO - LOOP

'This program displays a sentence 5 timesCLSDIM counter AS INTEGERFOR counter = 1 to 5 PRINT "Hello! How are you"NEXT

'This program displays a sentence 5 timesCLSDIM counter AS INTEGERcounter = 0DO    PRINT "Hello! How are you"    counter = counter + 1LOOP UNTIL counter = 5

 

Qbasic Tutorial for beginners and children (Under Construction)

The WHILE WEND statement

The WHILE WEND statement is another way to execute a loop. The DO LOOP statement, however, provides a better way to execute loops.

Code OutputDIM x AS INTEGERx = 0WHILE x < 5   x = x + 1   PRINT xWEND

12345

[ Previous Index Next ]

     pages viewed since January  19 2002

The GOTO statement

Page 27: qbasic

The GOTO statement branches to a specific line number or to the first statement after a specified label. 

In  the example below the GOTO statement braches to the instruction after the "label1" label until the value of variable "x" is equal to 5. 

Code Output  DIM x AS INTEGER  x = 0label1:  x = x + 1  PRINT x  IF x < 5 THEN     GOTO label1  END IF

12345

You should advoid using the GOTO statement wherever possible. Programmers who used GW-BASIC, the predecessor of qbasic, used to put a lot of GOTO statements, branching in every directions, in their programs, thus making it difficult to maintain. It was called spaghetti codes. The above program is simpler to write if you use the DO LOOP statement instead.

The same as above using the DO - LOOP'This program displays a sentence 5 timesCLSDIM x AS INTEGERx = 0DO    PRINT x    x = x + 1LOOP UNTIL x = 5

 

However, in some cases, there are no alternatives. The GOTO statement is used in conjunction with the ON ERROR statement which is used to trap errors in your program.

Chapter 9

Page 28: qbasic

Using colours

The COLOR statement is used to set the screen display colours.

It can be used in the following ways:

To modify both the foreground and the background colour use:

COLOR [foreground colour] , [background colour]

To modify the foreground colour only, use:

COLOR [foreground colour]

To modify both the background colour only, use:

COLOR , [background colour]

The foreground colour and the background colour are represented by numbers

The table below Below list the colours and their corresponding numbers.

Number Colour Number Colour

0 Black 8 Grey

1 Blue 9 Light Blue

2 Green 10 Light Green

3 Cyan 11 Light Cyan

4 Red 12 Light Red

5 Magenta 13 Purple

6 Brown 14 Yellow

7 White 15 Light White

 

Page 29: qbasic

The following examples illustrate how to use the COLOR statement:

Example 1: Printing in red over blue

Program Code

COLOR 14, 1PRINT "This text is in Yellow over Blue"

Output on Screen This text is in Red over Blue   

If you want to get the whole background in blue use the CLS statement after setting the colours:

Example 2

Program Code

COLOR 4, 1CLSPRINT "This text is in Yellow over Blue"

Output on Screen This text is in Red over Blue    You should be careful about the use of colours. Some colour matching are not pleasant to the eyes.

The LOCATE statement

The LOCATE statement is used to move the cursor on the screen.

The syntax is:

LOCATE row, column

Example:

Page 30: qbasic

LOCATE 20, 30PRINT "20th row, 30th Column"

By default there are 25 rows and 80 columns in BASIC, but this can be modified depending upon the screen resolution you are working.

The example above displays the text "20th row, 30th column" at the 20th row and 30th column of the basic screen. Using the locate statement in BASIC may result into "weird behaviour" from your program. Try the following example CLSLOCATE 1, 20PRINT "Can you see me?"LOCATE 25, 20PRINT "Where are you?"SLEEP 

In the example above the sentence "Can you see me?" disappeared from the screen. So what happened? 

The problem lies with with the 4th and 5th lines of your code. When you use the PRINT statement without putting a semicolon or a comma sign at the end of the line, BASIC sends a line feed bringing the cursor to the next line. Since we were at the 25th row, the screen scrolls one line down and your original first line gets "on top of the screen".

To solve this problem put a semicolon at the end of the PRINT statement.

CLSLOCATE 1, 20PRINT "Can you see me?"LOCATE 25, 20PRINT "Where are you?";SLEEP

 

Page 31: qbasic

Using Procedures

As you continue progressing in programming, your program may become bigger and more complex to understand. The use of procedures will help you to simplify the code.

A procedure is a

To create a procedure:

Click on Edit  New Procedure

To view a procedure:

Click on View -> SUBs

or

Press F2

and choose you procedure from the list