QBasic Manual

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34
At a glance
Powered by AI
The document discusses an introduction to the QBASIC programming language and its use for teaching programming concepts.

QBASIC is a basic programming language that can be used to teach introductory computer programming concepts. It has facilities for problem solving, data management, graphics, and more and is well suited for beginner programming courses.

The different types of loops discussed are FOR-NEXT loops, DO-WHILE loops, DO-UNTIL loops, and WHILE-WEND loops.

QBasic Hands-On

Training
QBASIC HANDS-ON TRAINING MANUAL

An introductory manual on the fundamental concepts of


the QBASIC programming language to introduce computer
programming as a vital aspect of Computer Science
Education in Nigerian Secondary Schools

Compiled by: Okiemute Mariere


Aiwekhoe Erhunmwunse Bobby
2 QBasic Hands-On Training

An Introduction
to QBASIC
PROGRAMMING
Benson Idahosa University
5th – 6th July 2012

Introduction to QBASIC programming


QBasic Hands-On Training 3

QBASIC AS A TOOL FOR TEACHING


AND LEARNING PROGRAMMING IN
SECONDARY SCHOOL
QBasic is a translated language and needs to be present to run the programs written with it.
It is accepted by all interested parties as freeware and can be downloaded and used at will.

QBasic has all the necessary facilities to teach a first computer course in problem solving
programming, data filing and management, vector based graphics, pixel level raster
graphics, sound, and more.

You cannot teach (or learn) programming principles using the huge top end programming
packages which are the tools of trained and experienced computer professionals who,
themselves learnt QBasic in their earlier years.

QuickBasic 4.5 is a more advanced version that is a compiled language. It has library files
and other features more suited to teaching those who have completed an introductory
course and may be required to be taught more advanced principles with an emphasis on
teaching how to produce functional software or how to produce software to solve specialist
tasks. The capacity to teach how to make library and produce 'executables' (i.e programs
converted to machine code that can be run on a computer without the QuickBasic program
being present), using software that fits on a diskette (940K zipped or 2.2 meg installed)
makes the software unrivalled for teaching advanced computer programming principles for
Senior High School or College technical discipline students. There is no other software that
comes remotely close. You can teach a beginner's first course using Quickbasic if you want
to. The interface is the same as Qbasic, you just don't mention the additional features.

Introduction to QBASIC programming


4 QBasic Hands-On Training

THE CONCEPT OF FLOWCHARTING IN


PROGRAMMING
A certain planning is essential before any problem is solved. This planning is necessary
whether it is a problem in mathematics or an everyday problem like shopping.

When a problem is solved on a computer it is essential to work out in detail all the decisions
to be taken by the machine, the actions to be performed and the sequence in which these
are to be performed. This planning is aided by flow-charts.

A flowchart depicts in a pictorial form the sequence of steps performed for solving the
problem.

It identifies the steps needed in solving a problem and shows these steps with connecting
lines and arrows to indicate the order in which the steps are performed.

Flowchart is the most frequently used tool to develop a solution procedure. One should be
skilled in drawing flowcharts to be a successful programmer. The figure below illustrates
some of the most frequently used flowchart symbols.

Terminal – indicates the beginning or end of the solution procedure

Processing – indicates arithmetic operations

Input/Output – indicates an operation of reading or writing

Decision box – indicates a decision point. A test is performed (i.e a


condition is tested) and the program flow continues on each outgoing path
conditional to the answer to the test.

On page connector – indicates reference to another point in the


flowchart on the same page

Introduction to QBASIC programming


QBasic Hands-On Training 5

Off page connector – indicates reference to another point in the


flowchart on a different page

Flowlines – the different flowchart symbols shown above are


connected by flowlines to indicate the sequence in which the different steps
are performed.

These flowchart symbols are used in some of the examples given to illustrate how they are
applied.

Introduction to QBASIC programming


6 QBasic Hands-On Training

INSTALLING AND LAUNCHING THE


QBASIC IDE
Step 1

Get the qbasic compiler by copying or downloading a copy of the qb45.zip folder which you
can get through google.com

Step 2

Extract the qbasic.zip folder to the root drive of the computer, mostly Local Disk C:

Step 3

Open Command Prompt by Clicking

Start>>All Programs>>Accessories>>Command Prompt from a Windows XP computer

Step 4

Type qb.exe on the command prompt and press enter to launch the QBasic environment

From here you can do the following:

Introduction to QBASIC programming


QBasic Hands-On Training 7

* Type a Program into Qbasic Editor


* Run the Program
- To RUN Program Press Shift + F5 Key.
- If Qbasic detects any errors, program will not RUN
- Qbasic Highlights the program line where error occurred
- Display a window on screen regarding Error Description
- If No Errors then, Notice the Program OutPut on the Screen
- Press SPACE BAR to go back to Qbasic Editor

* Save the Program


- To SAVE Program Press Alt- F Key.
- Notice TWO different SAVE Selection:
SAVE : it saves the file , if file created is new it ask for file name.
SAVE AS : it saves file under new name
- Type FILE NAME i.e. TEST.BAS
- Press ENTER KEY to save a file.

* Quit QBasic
To QUIT QBasic Program :
- Press Alt- FX Key

Introduction to QBASIC programming


8 QBasic Hands-On Training

QBASIC PROGRAMMING FOR HIGH


SCHOOL
THE FUNDAMENTALS
STRUCTURE OF A QBASIC PROGRAM

- QBasic editor is a full screen, context sensitive, syntax sensitive and self – correcting
tool for writing programs.

- Using the editor is one of the simplest tasks.

- Each program must contain :

1. Heading

2. Body

DATA TYPES

Data is differentiated into various types. The type of data element restricts the data element
to assume a particular set of values.

The Basic data types are:

String (STR) - This string is a special type. It can contain characters like ‘A’ or ‘ƒ’. Strings are
always notated with double quotation marks around them (“). The length of the character-
list can range up to 64k.

Integer (INT) - This data type is the most used data type of all. You can store only non-
decimal numbers in an integer. Since an integer contains 16 bits, you can only store values
from - 32768 up to 32767.

Long (LNG) - Long integers are not used that often, since mostly integers work fine. Long
integers are actually the same as normal integers, so only non-decimal numbers. However, a
long integer contains 32 bits, allowing you to store values from –2147483648 to
2147483647.

Single (SGL) – This type of data type can accommodate decimal numbers. Singles are 32 bit
and you can store values from around 9e40 to 9e-39.

Double (DBL) – Double can also contain decimal numbers. The only difference is that
doubles are 64 bits large, thus providing space for values from around 9 e305 to 9e-310.

Introduction to QBASIC programming


QBasic Hands-On Training 9

IDENTIFIERS

Identifiers are names given to various program elements, such as, variable, constant, arrays,
functions, sub-program etc

They are further classified into:

* Variable

*Constant
Reserved word: There are certain reserved words, called Keywords that have standard,
predefined meanings in QBasic. These Keywords can be used only for their intended
purpose; they cannot be used as programmer defined identifiers.

CONSTANTS

A Constant is an entity whose value does not change during execution of program.
Constants are of different types :

1. Integer Constant - An Integer(Decimal) value within range : –32768 to +32767


2. Long integer Constant - A Long Integer(Decimal) value within range : –
2,147,483,648 to +2,147,483,647
3. Floating-point Constant - Positive or Negative numbers in exponential form
4. Single Precision : Range -3.37E+38 to 3.37E+38
5. Double Precision : Range -1.67D+308 to 1.67D+308
6. String Constant - 1 or more characters enclosed in double quotes. Includes all
characters in the ASCII set except : double quotes, carriage return, line feed
characters. The Maximum number of characters allowed in a string is 32,767.

VARIABLE

A variable is a reference that can change its value during the execution of a program. In
QBasic, variables can be of the basic data types or user defined data type. A variable name
is used to refer to a value.

Uses of Variable:

• Temporary storage of data

• Storage of data during computation

• Menu choice by the user

• Running counter for loops

• Reading data from devices

Introduction to QBASIC programming


10 QBasic Hands-On Training

• Writing data to devices etc...

Variable Name:

• Can be 1 to a maximum of 40 characters long

• Must begin with a letter (A...Z, a...z )

• Cannot contain other than letters ,numbers ,period and type declaration characters(
$,%,#,&,! )

• Cannot begin with FN unless it is a function.

• Cannot be a reserved word.( CLS , PRINT,DIM …)

• Can be written as: I , N , NAME$ , RADIUS, MAXAMT%, PROMPT$ …

VARIABLE DECLARATION

In QBasic variables can be DECLARED using:


- Data type Character

- DIM statement etc….

Variable Name Declaration uses:


Suffix Data Type

$ String

% Integer

& Long Integer

! Single Precision

# Double Precision

For Example, RADIUS = 10

MAXAMT% = 1000

PROMPT$ = “ENTER YOUR CHOICE: “

USING DIM STATEMENT


SYNTAX:
DIM variable [AS type ] [,variable [AS type] ...]

where Variable is the name of allocated space in the memory

Introduction to QBASIC programming


QBasic Hands-On Training 11

AS type: basic data type

For Example,

DIM A AS INTEGER, NAME AS STRING, AGE AS INTEGER

Introduction to QBASIC programming


12 QBasic Hands-On Training

LET’S GET PROGRAMMING


FIRST QBASIC PROGRAM

The following program should be typed and then run in the QBASIC editor. It displays 2 lines
on the screen

REM MY FIRST QBASIC PROGRAM


CLS
PRINT “WELCOME TO QBASIC PROGRAMMING”
PRINT “This is my first QBasic program”
END
Output

WELCOME TO QBASIC PROGRAMMING

This is my first QBasic program

REM Statement: Allows explanatory remarks to be inserted in a program


Syntax:

REM text

CLS Statement: Clears the screen.


Syntax:
CLS

PRINT Statement: Allows text to be sent to the screen when the text is placed in double
quotes (“ ”)
Syntax:
PRINT “Text to be displayed”

ARITHMETIC OPERATORS

QBasic provides ARITHMETIC operators for comparing the values of two expressions.

+ Addition

- Subtraction

* Multiplication

/ Division (Real)

\ Division (Integer)

Introduction to QBASIC programming


QBasic Hands-On Training 13

^ Exponent

MOD Remainder

HIERARCHY OF OPERATIONS

The order of priority or precedence in which the arithmetic operations are performing arithmetic
statement is called the hierarchy of operations.

PRIORITY OPERATORS
1ST Parentheses – All brackets are evaluated first.

Note: QBASIC allows only parentheses i.e ( )

2ND Exponentations – All multiplications & divisions


are performed next

Note: Multiplication & division will be


performed in the order in which they appear in
the statement while scanning the expression
from left to right

3RD Multiplication & Division – All multiplications &


divisions are performed next.

Note: Multiplication & division will be


performed in the order in which they appear in
the statement while scanning the expression
from left to right.

4TH Mod & Integer Division – All mod & integer


divisions would be performed next.

5TH Addition & Subtraction – These operations are


performed last.

Note: Addition & subtraction will be performed


in the order in which they appear in a statement.

RELATIONAL OPERATORS

QBasic provides six relational operators for comparing the values of two expressions.

< Less than exp1 < exp2

<= Less than or equal to exp1 <= exp2

Introduction to QBASIC programming


14 QBasic Hands-On Training

> Greater than exp1 > exp2

>= Greater than or equal to exp1 >= exp2

= Equal to exp1 = exp2

<> Not equal to exp1 <> exp2

LOGICAL OPERATORS

QBasic provides three logical operators for joining two or more relational expressions.

AND - Operator will produce result as true only if two operands have true value

OR - Operator will produce result as false only if two operands have false value

NOT – Operator will produce result as true if operand is false and vice versa

LET ASSIGNMENT STATEMENT

LET Statement is used to assign a value to a variable. The value can be an expression or a
literal and must be the same type as the variable.

Syntax:

LET] variable = expression

The [LET] itself is optional. The variable can be assigned without explicitly using the word
[LET]

For Example:

a = 10:b = 5
LET area = 0.5 * BASE * HEIGHT
QUE$ = “HOW ARE YOU? “

SOME EXAMPLES ON VARIABLE DECLARATION

Example 1

REM A PROGRAM TO DEMONSTRATE USE OF DATA TYPE CHARACTER


CLS
NAME$ = "SHREEJI CONSULTANCY SERVICE"
RANK% = 21
PRINT NAME$, RANK%
END
Output
SHREEJI CONSULTANCY SERVICE 21

Introduction to QBASIC programming


QBasic Hands-On Training 15

Example 2

REM A PROGRAM TO DEMONSTRATE USE OF DIM STATEMENT


DIM CMPNAME AS STRING
DIM RANK AS INTEGER
CLS
CMPNAME = "SHREEJI COUNSALTANCY SERVICE“
RANK = 21
PRINT CMPNAME, RANK
END

Output
SHREEJI CONSULTANCY SERVICE 21

GOTO STATEMENT

GOTO Statement is an Unconditional branch. i.e. Program control will continue with the
line or label that the GOTO references. The Unconditional branch can only be at the same
level as the GOTO statement. You cannot use GOTO to enter or exit a subroutine or
function.

Syntax:
GOTO line number / line label

line number - A Valid Line Number i.e. 0 to 65529

line label - A Valid Line Label , String with a letter can’t exceed 40 characters in length and
always terminated with colon

For Example

REM A PROGRAM TO DEMONSTRATE USE OF GOTO


DIM I AS INTEGER
START: CLS
LET I = 10
PRINT “ I = “; I
GOTO START
END

END STATEMENT

Ends a program, procedure, block, or user-defined data type. If no argument is supplied,


END ends the program and closes all files.

Introduction to QBASIC programming


16 QBasic Hands-On Training

Syntax:
END [{DEF | FUNCTION | IF | SELECT | SUB | TYPE}]

Example

A PROGRAM TO DEMONSTRATE USE OF END


CLS
PRINT "WELCOME TO QBASIC "
PRINT "PROGRAM over."
END
Output
WELCOME TO QBASIC

PROGRAM over.

STOP STATEMENT

The stop state halts the program execution.

Syntax :

STOP

Example:

REM PROGRAM TO DEMONSTRATE USE OF STOP


FOR i% = 1 TO 10
PRINT i%
IF i% = 5 THEN STOP
NEXT i%
END

Output
1
2
3
4
6
7
8
9
10

Introduction to QBASIC programming


QBasic Hands-On Training 17

SOME MATHEMATICAL FUNCTIONS

ABS - returns the absolute value of a number.

PRINT ABS (45.5 - 100.0)

Output is 55.5

INT - returns the largest integer less than or equal to a numeric expression.

COS, SIN, TAN - returns the cosine, sine, and tangent of a specified angle.

SQR - Returns the square root of a numeric expression.

PRINT SQR(25), SQR(2)


Output is: 5 1.414214

SGN - returns a value indicating the sign of a numeric expression, 1 if the expression is
positive, 0 if it is zero, or -1 if it is negative

EXP - returns e raised to a specified power, where e is the base of natural logarithms

VAL - converts a string representation of a number to a number.

SWAP - Exchanges the values of two variables.

Syntax:

SWAP variable1, variable2

where variable1 and variable2 are two variables of the same type.

INPUT STATEMENT

INPUT : reads input from the keyboard or file.


LINE INPUT: reads a line of up to 255 characters from the keyboard or file.

Syntax:

INPUT [;] ["prompt"{; | ,}] variablelist

LINE INPUT [;] ["prompt";] variable$

This is one of the most commonly used methods in QBasic for entering values of variables.

"prompt" - An optional literal string that is displayed before the user enters data. A
semicolon after prompt appends a question mark to the prompt string.

Introduction to QBASIC programming


18 QBasic Hands-On Training

variablelist, variable$ - One or more variables, separated by commas, in


which data entered from the keyboard or read from a file is stored. Variable names can
consist of up to 40 characters and must begin with a letter. Valid character: A-Z, 0-9, and
period (.)

NOTE:

INPUT uses a comma as a separator between entries.

LINE INPUT reads all characters up to a carriage return.

For keyboard input, a semicolon immediately after INPUT keeps the cursor on the same line
after the
user presses the Enter key. INPUT can be accepted into STRING, NUMERIC, ARRAY, and
RECORD ELEMENTS.

Example 1:

CLS

INPUT " NAME : ", Name$

INPUT " AGE : ", Age$

PRINT

PRINT " NAME : "; Name$

PRINT " AGE : "; Age$

END

Output
NAME : John Grant

AGE : 36

NAME : John Grant

AGE : 36

If value entered was of incorrect type or too many or too few values were entered then
compiler gives following error “redo from start”

Example 2

Write a program in QBASIC to calculate simple interest

REM CALCULATION OF SIMPLE INTEREST


REM AUTHOR ESTHER DATE 7 JUNE 2012

Introduction to QBASIC programming


QBasic Hands-On Training 19

CLS
DIM P, R, T, SI AS SINGLE
PRINT “ENTER THE VALUES OF P, R, T”
INPUT P, R, T
SI = P * R * T / 100
PRINT SI
END
Output

ENTER THE VALUES OF P, R, T


1000 5 0.2
10

Example 3

Write a program to calculate the average age of a tennis team

REM CALCULATION OF AVERAGE AGE


CLS
DIM A1,A2,A3,A4,TOT,AVERAGE AS INTEGER
PRINT “ENTER THE VAL OF A1,A2,A3,A4”
PRINT
INPUT A1,A2,A3,A4
TOT = A1 + A2 + A3 + A4
AVERAGE = TOT / 4
PRINT AVERAGE
END
Output

ENTER THE VAL OF A1,A2,A3,A4


22 25 23 20
25

DO IT YOURSELF!
Write a QBASIC program to calculate a student’s average score of 4 subjects taken in an
exam and the scores entered from the keyboard

Introduction to QBASIC programming


20 QBasic Hands-On Training

SUGGESTED CLASSROOM EXERCISE 1


FORMULA CALCULATOR

To calculate different formulas such as Areas, Perimeters, and Volumes of shapes by


accepting different values from users and displaying the result accurately.

This is exercise is to be done by students with guidance from the teacher

Introduction to QBASIC programming


QBasic Hands-On Training 21

DECISION – MAKING IN QBASIC


CONDITIONAL STATEMENT

A Conditional statement allows selective processing of a statement or a group of


statements. There are two forms of conditional statement:

1. if-then-else statement
2. if-then-elseif … else statement

IF-THEN-ELSE STATEMENT

It is used to test the condition or to take decision. Sometimes it is also referred as decision-
making statement.

Syntax:

if (expression) then statement


if (expression) then statement [else statement ]
Example
Conditional Expression

if(n MOD 2 <> 0)then


PRINT “ It is an odd number”

IF-THEN-ELSEIF … ELSE STATEMENT

Allows conditional execution of a group of statements. However, there are many situations
when two groups of statements are given and it is desired that one of them be executed if
some condition is true and the other be executed if the condition is false. In such situations,
we make use of the if-else statement whose general format is:

Syntax:

IF condition1 THEN
[statementblock-1]
[ELSEIF condition2 THEN
[statementblock-2]]
...
[ELSE
[statementblock-n]]
END IF
Example 1

Introduction to QBASIC programming


22 QBasic Hands-On Training

REM A PROGRAM TO DETERMINE IF A NUMBER IS ODD OR EVEN


DIM num AS INTEGER
CLS
INPUT “ Enter any number : “; num
if (num MOD 2 = 0 ) then
PRINT “Even ”
else
PRINT “Odd ”
end if
END

Output
Enter any number : 4
Even
Enter any number : 7
Odd

Example 2

While purchasing certain items a discount of 10% is offered if the quantity purchased is
more than 1000. If quantity and price per item is input through the keyboard, write a
QBASIC program to calculate the total expenses

REM CALCULATION OF TOTAL EXPENDITURE


CLS
DIM QTY, RATE, DIS AS INTEGER
DIM TOTEXP AS SINGLE
PRINT “ENTER THE VALUES OF QTY, RATE”
INPUT QTY, RATE
IF QTY > 1000 THEN DIS = 10
TOTEXP = QTY*RATE – DIS*RATE/100
PRINT TOTEXP
END
Example 3

If 3 numbers are input through the keyboard, write a QBASIC program to determine the
largest of the 3 numbers.

REM DETERMINE THE LARGEST OF 3 NUMBERS


CLS
DIM LARGEST AS INTEGER
PRINT “ENTER THE VALUES OF THREE INTEGERS”

Introduction to QBASIC programming


QBasic Hands-On Training 23

INPUT A, B, C
LARGEST = A
IF B > LARGEST THEN LARGEST = B
IF C > LARGEST THEN LARGEST = C
PRINT LARGEST
END

DO IT YOURSELF!
If 3 numbers are input through the keyboard, write a QBASIC program to determine the
smallest of the 3 numbers

SELECT CASE STATEMENT

When one of the many alternatives is to be selected, we can design a program using if
statement to control the selection. However, the complexity of such a program increases
dramatically when the number of alternatives increases. The program becomes difficult to
read and follow. Some times it may even confuse the person who designed it.

In ‘QBasic’, there is a built-in multi-way decision statement, which is known as SELECT CASE
statement. The SELECT CASE statement tests the value of a given variable/expression
against a list of case values and when a match found, a block of statements associated with
that case is executed.

The general form of the SELECT CASE statement is as shown below:

SELECT CASE (testexpression)


CASE expressionlist1
[statementblock-1]
[CASE expressionlist2
[statementblock-2]]
...
[CASE ELSE
[statementblock-n]]
END SELECT
testexpression: is any numeric or string expression

expressionlist: One or more expressions to match testexpression. The IS keyword must


precede any relational operators in an expression

statementblock1: One or more statements on one or more lines


statementblock2

Introduction to QBASIC programming


24 QBasic Hands-On Training

...
statementblockn

Example 1

DIM A, B, RESULT AS SINGLE, OP AS STRING


INPUT "Enter A B OP : " A, B, OP
SELECT CASE OP
CASE IS = "+"
PRINT " ADDITION "
RESULT = A + B
PRINT "RESULT = "; RESULT
CASE IS = "-"
PRINT " SUBTRACTION "
RESULT = A - B
PRINT "RESULT = "; RESULT
CASE IS = "*"
PRINT " MULTIPLICATION "
RESULT = A * B
PRINT "RESULT = "; RESULT
CASE IS = "/"
PRINT " REAL DIVISION "
RESULT = A / B
PRINT "RESULT = "; RESULT
CASE ELSE
PRINT "INVALID OPERATOR "
END SELECT
END

Output

Introduction to QBASIC programming


QBasic Hands-On Training 25

Enter A B OP : 3 2 +
ADDITION
RESULT = 5
Enter A B OP : 10 7 -
SUBTRACTION
RESULT = 3
Enter A B OP : 10 7 *
MULTIPLICATION
RESULT = 70
Enter A B OP : 6 3 /
REAL DIVISION
RESULT = 2
Enter A B OP : 8 3 =
INVALID OPERATOR

Example 2

REM A PROGRAM TO FIND ROOTS OF QUADRATIC EQUATION


REM Ax^2 + Bx + C = 0
CLS
DIM A, B, C, DELTA AS SINGLE
INPUT "Enter A B C : "; A, B, C
DELTA = B * B - 4 * A * C
PRINT "DELTA = "; DELTA
SELECT CASE DELTA
CASE IS > 0
PRINT "REAL ROOTS"
CASE IS < 0
PRINT "COMPLEX ROOTS"
CASE IS = 0
PRINT "EQUAL ROOTS"
END SELECT
END
Output
Enter A B C : 2 4 2
EQUAL ROOTS
Enter A B C : 4 1 1
COMPLEX ROOTS
Enter A B C : 2 5 3
REAL ROOTS
CONTROL STRUCTURES

Introduction to QBASIC programming


26 QBasic Hands-On Training

To control the flow of execution of programs, the ‘QBasic’ language provides very powerful
facilities.

There are basically three types of control structures:

1. Sequential
2. Selective or decision making or conditional
3. Repetitive or iterative or looping

Repetitive or Iterative or Looping

The repetitive structure allows a sequence of program statements to be executed several


times though those statements appear only once in the program.

It consists of:
* an entry point that may include initialization of certain variables
* a loop Continuation Condition
* a loop body
* an exit point

A repetitive structure must always be entered at the entry point to ensure that the
appropriate initialization takes place. The loop body consists of statements that are
normally executed several times.

The exit point is the first statement following the loop body. The number of repetitions in a
repetitive structure is controlled by a loop continuation condition, which is tested once for
each execution of the loop body.

There are three major loop structures in QBASIC language

1. For Loop
2. Do ... While/Until Loop
3. While ... Wend Loop

FOR Loop

The for loop is a very flexible and powerful repetitive structure (PRE-TEST LOOP). If you
know the number of times a block of statement(s) that you want to execute a specific
number of times then for - loop is most appropriate.

The general form of the for loop is:

FOR counter = start TO end [STEP increment]

[statementblock]

Introduction to QBASIC programming


QBasic Hands-On Training 27

NEXT [counter]

Where

counter: A numeric variable used as the loop counter

start: The initial value of the end counter

end: The final value of the end counter

increment: The amount the counter is changed each time through the loop

Example 1

FOR I = 1 TO 5
PRINT I
NEXT I

Output

1
2
3
4
5

Example 2
FOR I = 7 TO -6 STEP –3
PRINT I
NEXT I
Output

7
4
1
-2
-5

Example 3

REM PRINT 1st N NUMBER. ALSO CALCULATE SUM & AVERAGE OF N NUMBERS
CLS
DIM I, N, SUM AS INTEGER
DIM AVG AS SINGLE

INPUT "ENTER N : "; N


SUM = 0

Introduction to QBASIC programming


28 QBasic Hands-On Training

FOR I = 1 TO N
PRINT I
SUM = SUM + I
NEXT I
AVG = SUM / N
PRINT "SUM : "; SUM
PRINT "AVERAGE : "; AVG
END

Output
ENTER N : 5
1
2
3
4
5
SUM : 15
AVERAGE : 3

Example 4

REM PRINT N,N*N,N*N*N AND ALSO PRINT SUM OF N, N*N , N*N*N


DIM N, SUMN, SUMSQ, SUMCUBE AS SINGLE
DIM I AS INTEGER
INPUT "ENTER N : "; N
PRINT " N N*N N*N*N “
SUMN = 0: SUMSQ = 0: SUMCUBE = 0
FOR I = 1 TO N
PRINT I, I * I, I * I * I
SUMN = SUMN + I
SUMSQ = SUMSQ + I * I
SUMCUBE = SUMCUBE + I * I * I
NEXT I
PRINT "SUMN = "; SUMN
PRINT "SUM OF SQUARE = "; SUMSQ
PRINT "SUM OF CUBE = "; SUMCUBE
END

Output

Introduction to QBASIC programming


QBasic Hands-On Training 29

ENTER N : 5
N N*N N*N*N
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
SUMN = 15
SUM OF SQUARE = 55
SUM OF CUBE = 225

Example 5

REM CALCULATE FACTORIAL OF N.


CLS
DIM I, N, FACT AS INTEGER
INPUT "ENTER N : "; N
FACT = 1
FOR I = 1 TO N
FACT = FACT * I
NEXT I
PRINT “ N! = "; FACT
END
Output
ENTER N : 5
5! = 120
ENTER N : 4
4! = 24
ENTER N : 6
6! = 720

Example 6

REM PRINT 1st N TERMS OF ODD/EVEN NUMBER


DIM I, J, N AS INTEGER
INPUT "ENTER N "; N
PRINT "1ST N ODD NUMBERS ARE AS FOLLOWS “
J = 1
FOR I = 1 TO N
PRINT J
J = J + 2
NEXT I
PRINT "1ST N EVEN NUMBER ARE AS FOLLOWS “
J = 0
FOR I = 1 TO N

Introduction to QBASIC programming


30 QBasic Hands-On Training

PRINT J
J = J + 2
NEXT I
END

Output
ENTER N : 5
1ST N ODD NUMBERS ARE AS FOLLOWS
1
3
5
7
9
1ST N EVEN NUMBER ARE AS FOLLOWS
0
2
4
6
8

Do ... While Loop

The Do … While loop is a post-test loop, whose general format is:

Do

body of loop

[ { While } ] (expression)

body of loop may contain one or more statements.

The do-while type of loop repeats the body of the loop while expression is TRUE

Example

REM
CLS
DIM count AS integer
count = 0
do
PRINT “ Count = ”,count
count = count + 1
while (count < 10)
END

Output

Introduction to QBASIC programming


QBasic Hands-On Training 31

Count = 0
Count = 1
Count = 2
Count = 3
Count = 4
Count = 5
Count = 6
Count = 7
Count = 8
Count = 9

Do ... Until Loop

The Do … Until loop is a post-test loop, whose general format is:

Do
body of loop
[{Until}](expression)
body of loop may contain one or more statements

Repeat Body of loop Until an expression becomes TRUE

While ... Wend Loop

The While … Wend loop is a pre-test loop, whose general format is:

While (expression)
body of loop
Wend
body of loop may contain one or more statements

Repeat Body of loop While an expression is TRUE

Example

REM
DIM count AS integer
CLS
count = 1
While ( count <= 10 )
PRINT “Count = ”,count

Introduction to QBASIC programming


32 QBasic Hands-On Training

count = count + 1
Wend
END

Output
Count = 1
Count = 2
Count = 3
Count = 4
Count = 5
Count = 6
Count = 7
Count = 8
Count = 9
Count = 10

ARRAYS

An ordered finite collection of data items, each of the same type, is called an array, and the
individual data items are its elements.

Only one name is assigned to an entire array, and individual elements are referenced by
specifying a subscript. A subscript is also called an index.

In QBasic,
* Subscripts Range: - 32768 to + 32767

* Maximum 60 Dimension are allowed

* Array has Maximum Size Limit: 64 K

Arrays, like simple variable, need to be declared before use. An array declaration is of the
form :

DIM array-name(subscript) AS TYPE

subscript : Lower limit TO Upper limit

: - 32768 TO + 32767

: Maximum 60 dimension

: Decide the SIZE of ARRAY

For example,

DIM a(6) AS INTEGER

Introduction to QBASIC programming


QBasic Hands-On Training 33

a(0) a(1) a(2) a(3) a(4) a(5) a(6)

1st element is referenced by a (0), 2nd element is referenced by a (1), and so on.

* The default Lower bound is zero.

* Maximum 60 Dimension are allowed.

* Array has Maximum size Limit : 64 K.

When an array is referenced with a subscript that is outside the declaration, message “
Subscript out of range “ appears.

EXIT STATEMENT

Exit Statement: Exits a DO or FOR loop, a FUNCTION or SUB procedure, or a DEF function.

Syntax:
EXIT {DEF | DO | FOR | FUNCTION | SUB}

DEF Exits a DEF function.

DO Exits a DO loop.

FOR Exits a FOR loop.

FUNCTION Exits a FUNCTION procedure.

SUB Exits a SUB procedure.

Introduction to QBASIC programming


34 QBasic Hands-On Training

SUGGESTED PRACTICE PROJECTS


FROM LESSONS LEARNT
From the lessons learnt above, you now have the required knowledge to write any of the
following programs in a simple way. Remember, Practice makes Perfect!!!

 Quadratic Equation calculator


 Student Termly Result
 Maths Calculator
 Measuring Unit Converter

Introduction to QBASIC programming

You might also like