KEMBAR78
Main Intro To QBASIC | PDF | Algorithms | Control Flow
0% found this document useful (0 votes)
57 views34 pages

Main Intro To QBASIC

Uploaded by

noumsi brice
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views34 pages

Main Intro To QBASIC

Uploaded by

noumsi brice
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

PREAMBLE:

Computers can perform different tasks. In school, students use computers for tasks such as writing papers,
searching for articles, sending email, and participating in online classes. At work, people use computers to
analyze data, make presentations, conduct business transactions, communicate with customers and coworkers,
control machines in manufacturing facilities, and do many other things. At home, people use computers for tasks
such as paying bills, shopping online, communicating with friends and family, and playing computer games. And
don’t forget that cell phones, iPods, BlackBerries, car navigation systems, and many other devices are computers
too. The uses of computers are almost limitless in our everyday lives. Computers can do such a wide variety of
things because they are programmed to do so. This means that computers are not designed to do just one job,
but to do any job that their programs tell them to do. By definition, a computer system is a device that accepts
input known as data from the user, process the inputs based on a set of instructions called program and
produce the results or output also called information.

A program is a set of instructions that a computer follows to perform a task, for example, Microsoft Word and
Adobe Photoshop. Microsoft Word is a word processing program that allows you to create, edit, and print
documents with your computer. Adobe Photoshop is an image editing program that allows you to work with
graphic images, such as photos taken with your digital camera. These Programs are commonly referred to as
software. Software is essential to a computer because it controls everything the computer does. All of the
software that we use to make our computers useful is created by individuals working as programmers or
software developers. A programmer, or software developer, is a person with the training and skills necessary to
design, create, and test computer programs. Computer programming is an exciting and rewarding career. Today,
you will find programmers’ work used in business, medicine, government, law enforcement, agriculture,
academics, entertainment, and many other fields. This course introduces you to the fundamental concepts of
computer programming using the beginners’ language known as BASIC programming language.

OVERVIEW OF PROGRAMMING
Computer programming is a problem-solving approach. Basically, programmers develop programs when
encountered with challenges of proffering solutions to real life problems. A computer program has immense
potential for saving time/energy, as most computational tasks that are repetitive or can be generalized can be
done by computer programs. Programs can be built using programming languages which are classified into three
categories viz;
a) Machine language: This is the only language the computer understands and is also called a binary language. It
is made up of 0’s and 1’s.

b) Low Level languages: These are assembly languages that use mnemonics to represents computer operations.
The mnemonics are translated into machine language using a translator program known as the assembler. An
Assembly language is this symbolic language used to enter machine code instructions using easy-to-remember
mnemonics. The assembler converts assembly language statements into machine codes.

c) High Level Languages (HLL): These are computer languages that allow the programmer or software developer
to develop program codes using human understandable expressions. HLL uses an intermediate translator
program known as Compiler or interpreter to converts program codes written in HLL to machine understandable
0’s and 1’s for the computer to execute the programs. Examples include; BASIC, Java, C++, VB .Net, python,
Pascal, FORTRAN, PHP, etc.

This course intends to introduce students to computer programming using high level programming languages.
We shall adopt the beginners programming language known as BASIC (Beginner’s All-Purpose Symbolic
Instruction Code) to get students acquainted with computer programs. The Basic programming language is
interpreted and therefore requires an interpreter program in order to run any program written in the Basic
programming language.

ALGORITHMS
Recall that programming is a problem-solving approach. To develop programs that will solve human problems
efficiently, there is a need for a step-by-step representation of the solutions before transforming them into
computer programs using specific computer languages. An algorithm is a representation of a solution to a

1
problem. It is procedure for solving a problem in finite number of steps. Algorithms provide step-by-step
methods of accomplishing a task.
The term algorithm originally referred to any computation performed via a set of rules applied to numbers
written in decimal form. The word is derived from the phonetic pronunciation of the last name of Abu Ja'far
Mohammed ibn Musa alKhowarizmi, who was an Arabic mathematician who invented a set of rules for
performing the four basic arithmetic operations (addition, subtraction, multiplication and division) on decimal
numbers.

An algorithm is procedure consisting of a finite set of unambiguous rules (instructions) which specify a finite
sequence of operations that provides the solution to a problem, or to a specific class of problems for any
allowable set of input quantities (if there are inputs). In other word, an algorithm is a step-by-step procedure to
solve a given problem Alternatively, we can define an algorithm as a set or list of instructions for carrying out
some process step by step.

In the problem-solving phase of computer programming, you will be designing algorithms. This means that you
will have to be conscious of the strategies you use to solve problems in order to apply them to programming
problems. These algorithms can be designed or implemented using flowcharts or pseudocode.

FLOWCHARTS
Flowcharting is a tool developed in the computer industry, for showing the steps involved in a process. A
flowchart is a diagram made up of boxes, diamonds and other shapes, connected by arrows - each shape
represents a step in the process, and the arrows show the order in which they occur. Flowcharting combines
symbols and flow lines, to show figuratively the operation of an algorithm.

Flowcharting Symbols

There are 6 basic symbols commonly used in flowcharting: Terminal, Process, input/output, Decision, Connector
and Predefined Process. This is not a complete list of all the possible flowcharting symbols; it is the list of ones
used most often in structured programming.

Symbol Name Function

Process Indicates any type of internal


operation inside the Processor
or Memory

input/output Used for any Input / Output


(I/O) operation. Indicates that
the computer is to obtain data
or output results

Decision Used to ask a question that can


be answered in a binary format
(Yes/No, True/False)

Connector Allows the flowchart to be


drawn without intersecting lines
or without a reverse flow.

Predefined Process Used to invoke a subroutine or


an interrupt program.

Terminal Indicates the starting or ending


of the program, process, or
interrupt program.

2
Flow Lines Shows direction of flow

Generally, there are many standard flowcharting symbols.

General Rules for flowcharting

1. All boxes of the flowchart are connected with Arrows. (Not lines)

2. Flowchart symbols have an entry point on the top of the symbol with no other entry points. The exit point for
all flowchart symbols is on the bottom except for the Decision symbol.

3. The Decision symbol has two exit points; these can be on the sides or the bottom and one side.

4. Generally a flowchart will flow from top to bottom. However, an upward flow can be shown as long as it does
not exceed 3 symbols.

5. Connectors are used to connect breaks in the flowchart. Examples are:

• From one page to another page.

• From the bottom of the page to the top of the same page.

• An upward flow of more than 3 symbols

6. Subroutines and Interrupt programs have their own and independent flowcharts

7. All flow charts start with a Terminal or Predefined Process (for interrupt programs or subroutines) symbol. 8.
All flowcharts end with a terminal or a contentious loop.

Flowcharting uses symbols that have been in use for a number of years to represent the type of operations
and/or processes being performed. The standardized format provides a common method for people to visualize
problems together in the same manner. The use of standardized symbols makes the flow charts easier to
interpret; however, standardizing symbols is not as important as the sequence of activities that make up the
process.

Examples of Algorithms and Flowcharts

Example 1: Design an algorithm and the corresponding flowchart for adding the tests cores as given below:

26, 49, 98, 87, 62, 75

a) Algorithm

1. Start

2. Sum = 0

3. Get the first testscore

4. Add first testscore to sum

5. Get the second testscore

6. Add to sum

7. Get the third testscore

8. Add to sum

9. Get the Forth testscore

10. Add to sum

3
11. Get the fifth testscore

12. Add to sum

13. Get the sixth testscore

14. Add to sum

15. Output the sum

16. Stop

b) The corresponding flowchart is as follows:

Start

Sum=0

Get 1st test score

Add 1st test score to sum

Get 2nd test score

Add 2nd test score to sum

Get 3rd test score

Add 3rd test score to sum

Get 4th test score

Add 4th test score to sum

Get 5th test score

4
A

Add 5th test score to sum

Get 6th test score

Add 6th test score to sum

Print sum

The algorithm and the flowchart above illustrate the steps for solving the problem of adding six test scores.
Where one test score is added to sum at a time. Both the algorithm and flowchart should always have a Start
step at the beginning of the algorithm or flowchart and at least one stop step at the end, or anywhere in the
algorithm or flowchart. Since we want the sum of six test scores, then we should have a container for the
resulting sum. In this example, the container is called sum and we make sure that sum should start with a zero
value by step 2.

Example 2: The problem with this algorithm is that, some of the steps appear more than once, i.e. step 5 get
second number, step 7, get third number, etc. One could shorten the algorithm or flowchart as follows:

1. Start

2. Sum = 0

3. Get a value

4. sum = sum + value

5. Go to step

3 to get next Value

6. Output the sum

7. Stop

5
Start

Sum=0

Get a value

Sum = sum + value

output

stop

This algorithm and its corresponding flowchart are a bit shorter than the first one. In this algorithm, step 3 to 5
will be repeated, where a number is obtained and added to sum. Similarly, the flowchart indicates a flow line
being drawn back to the previous step indicating that the portion of the flowchart is being repeated. One
problem indicates that these steps will be repeated endlessly, resulting in an endless algorithm or flowchart. The
algorithm needs to be improved to eliminate this problem. In order to solve this problem, we need to add a last
value to the list of numbers given. This value should be unique so that, each time we get a value, we test the
value to see if we have reached the last value. In this way our algorithm will be a finite algorithm which ends in a
finite number of steps as shown below. There are many ways of making the algorithm finite.

The new list of numbers will be 26, 49, 498, 9387, 48962, 1, -1. The value –1 is a unique number since all other
numbers are positive.

1. Start

2. Sum = 0

3. Get a value

4. If the value is equal to –1, go to step 7

5. Add to sum (sum = sum + value)

6. Go to step 3 to get next Value

7. Output the sum

8. Stop

Corresponding flowchart:

6
Start

Sum=0

Get a value

Value = -1 Sum = sum + value

Print sum

Start

PSEUDOCODE
Pseudocode is one of the tools that can be used to write a preliminary plan that can be developed into a
computer program. Pseudocode is a generic way of describing an algorithm without use of any specific
programming language syntax. It is, as the name suggests, pseudo code —it cannot be executed on a real
computer, but it models and resembles real programming code, and is written at roughly the same level of
detail.
Pseudocode, by nature, exists in various forms, although most borrow syntax from popular programming
languages (like C, Lisp, or FORTRAN). Natural language is used whenever details are unimportant or distracting.

In the algorithm design, the steps of the algorithm are written in free English text and, although brevity is
desired, they may be as long as needed to describe the particular operation. The steps of an algorithm are said
to be written in pseudocode. Many languages, such as Pascal, have a syntax that is almost identical to
pseudocode and hence make the transition from design to coding extremely easy. Examples of pseudocodes
include; suppose you are required to design an algorithm for finding the average of six numbers and the sum of
the numbers is given. The pseudocode will be as follows:

Start

Get the sum

Average = sum / 6

Output the average

Stop

This is the pseudo-code required to input three numbers from the keyboard and output the result.

Use variables: sum, number1, number2, number3 of type integer

Accept number1, number2, number3

Sum = number1 + number2 + number3

Print sum

7
End program

The following pseudo-code describes an algorithm which will accept two numbers from the keyboard and
calculate the sum and product displaying the answer on the monitor screen.

>= 80 Distinction

>= 60 Merit

>= 40 Pass

< 40 fail

The pseudo-code is

Use variables: mark of type integer

If mark >= 80 display “distinction”

If mark >= 60 and mark < 80 display “merit”

If mark >= 40 and mark < 60 display “pass”

If mark < 40 display “fail”

PROGRAMMING PARADIGMS
WHAT IT IS: The word paradigm is used a great deal when talking about programming languages. What does it
mean?
A programming paradigm is a style or “way” of programming. Some languages make it easy to write in some
paradigms but not others.

Some of the more common paradigms are

 Imperative — Control flow is an explicit sequence of commands.

 Declarative — Programs state the result you want, not how to get it.

 Structured — Programs have clean, goto-free, nested control structures.

 Procedural — Imperative programming with procedure calls.

 Functional (Applicative) — Computation proceeds by (nested) function calls that avoid any global state.

 Function-Level (Combinator) — Programs have no variables. No kidding.

 Object-Oriented — Computation is affected by sending messages to objects; objects have state and behavior.

o Class-based — Objects get their state and behavior based on membership in a class.

o Prototype-based — Objects get their behavior from a prototype object.

 Event-Driven — Control flow is determined by asynchronous actions (from humans or sensors).

 Flow-Driven — Computation is specified by multiple processes communicating over predefined channels.

 Logic (Rule-based) — Programmer specifies a set of facts and rules, and an engine infers the answers to
questions.

 Constraint — Programmer specifies a set of constraints, and an engine infers the answers to questions.

 Aspect-Oriented — Programs have cross-cutting concerns applied transparently.

Reflective — Programs manipulate their own structures.

 Array — Operators are extended to arrays, so loops are normally unnecessary.


8
Paradigms are not meant to be mutually exclusive; you can program in a functional, object-oriented, event-
driven style

TWO POPULAR PROGRAMMING PARADIGMS

Object-Oriented Programming Paradigm


OOP is based on the sending of messages to objects. Objects respond to messages by performing operations.
Messages can have arguments, so "sending messages" looks a lot like calling subroutines. A society of objects,
each with their own "local memory" and own set of operations has a different feel than the "monolithic
processor and single shared memory" feel of non-object oriented languages.
The first object-oriented language was Simula-67; Smalltalk followed soon after as the first "pure" object-
oriented language. Many languages designed from the 1980s to the present have been object-oriented, notably
C++, CLOS (object system of Common Lisp), Eiffel, Modula-3, Ada 95, Java, C#, Ruby

Structured Programming Paradigm


Programs have clean, goto-free, nested control structures. Structured programming is a kind of imperative
programming where the control flow is defined by nested loops, conditionals, and subroutines, rather than via
gotos. Variables are generally local to blocks (have lexical scope).

INTRODUCTION TO QBASIC
1. It is a user-friendly language.
2. It is widely known and accepted programming language.
3. It is one of the most flexible languages, as modification can easily be done in already existing program. 4.
Language is easy since the variables can be named easily and uses simple English phrases with mathematical
expressions.

RULES OF QBASIC
Every programming language has a set of rules that have to be followed while writing a program; following are
some rules of QBASIC language:
1. All QBasic programs are made up of series of statements, which are executed in the order in which they are
written.

2. Every statement should have at least one QBasic command word. The words that BASIC recognizes are called
keywords.

3. All the command words have to be written using some standard rules, which are called “Syntax Rules”. Syntax
is the grammar of writing the statement in a language. Syntax Errors are generated when improper syntax is
detected.

4. Basic program files must be saved with a file extension name of .bas. For a QBASIC program to run, it must be
saved.

DATA TYPES
Data is a collection of facts and figures that is entered into the computer through the keyboard. Data is of two
types:
1. CONSTANT: Data whose value does not change or remains fixed. A constant is a data object whose value
cannot be changed. There are two types of constants:

(a) NUMERIC CONSTANT: Numbers -negative or positive used for mathematical calculations e.g. –10, 20, 0

(b) ALPHANUMERIC CONSTANT / STRING: Numbers or alphabets written within double quotes (inverted commas
“ “). e.g. “Computer”, “Operating System”

2.VARIABLE: A variable is a data object whose value can be defined and redefined. A variable can simply be
referred to as a name which can contain a value. It is a data whose value is not constant and may change due to
some calculation during the program execution. A variable is actually a location in the computer’s memory,
which stores the values. Depending on what value is held, Variables are of two types:

9
 NUMERIC VARIABLE: The variable that holds a Numeric data values for arithmetic calculations (+, - ,*, / )
is called a Numeric Variable. e.g. A = 50, here A is the Numeric Variable. In numeric variables, the symbol
% means integer and it truncate real numbers eg: A% = 6.2 implies A%=6 A%=6.6 implies A% = 7 etc. the
symbols !, & and # represents single, long and double precision variables respectively.
 CHARACTER OR STRING VARIABLE: The variable that holds an Alphabetic, Alphanumeric or numeric
data value, which cannot be used for arithmetic calculations, is called Character Variable or String
Variable. This variable must end with a $ sign and the value it hold must be enclosed in inverted
commas. e.g. Name$ = “BringBackOurGirls”, here Name$ is a string Variable. If a variable holds a symbol
or text, it may be a character variable or a string variable. E.g; C$, ICT101$, CE$, etc.

Both constant names and variable names are user defined and must not start with a special symbol or
numeric values. QBASIC doesn’t allow keywords to be used as variable or constant names. Variables and
Constant names utilize a character set of A-Z and a-z alphabetic values,0-9 numeric values and a special dot
(.) symbol might be used.

ASSIGNMENT STATEMENTS
In programming, assignment is the term for setting a variable equal to some value. Assignment allocates
data values to the memory locations represented by the variables on the left-hand side of the said
statement. These statements assign an expression to a quantity. The general form is:
Let <variable> = <value/expression>

Where expression may be a variable, a numeric data and or an arithmetic expression, or combination of
each.

An assignment statement uses the equals sign (=), but this symbol does not have the same meaning as it has
in mathematics. In QBasic, the statement

x=x+1

means that the value x is to be incremented by 1 and the result stored into the memory location reserved
for the quantity represented by x. Examples of assignment statements include;

Let A = 15…... Assigning a numeric value to a variable

Let A = B………Assigning variable to a variable

Let C = A + B…. Assigning an expression to a variable

In QBASIC, assignment statements can also be written without including the LET

keyword: <variable> = <value/expression>

The keyword LET is optional in an assignment statement. Examples include;

A = 15……. Assigning a numeric value to a variable

A = B………Assigning variable to a variable

C = A + B…. Assigning an expression to a variable

OPERATORS
There are different types of operators in FORTRAN 95, the common ones include: arithmetic, relational and
logical.

10
ARITHMETIC OPERATORS: They include;

Operator Function Example Results


+ Addition 10 + 5 15
- Subtraction 10 - 5 5
* Multiplication 10 * 5 50
/ Division 10 / 5 2
^ Exponentiation 10 ^5 100000

RELATIONAL OPERATORS: Relational operators are operators that are placed between expressions and that
compare the results of the expressions. They are a set of binary relational operators that take any two
numeric or character variables of the same type and kind and return a logical result. These operators are
used in conditionals to construct tests. The relational operators in QBASIC are:

operator meaning example = Equal to IF a = 15 THEN… <> Not equal to IF a <> 15 THEN… < Less than IF a <
15 THEN… <= Less or equal to IF a <= 15 THEN > greater than IF a > 15 THEN… >= greater or equal to IF a >=
15 THEN…

operator meaning example


= Equal to IF a = 15 THEN…
<> Not equal to IF a <> 15 THEN…
< Less than IF a < 15 THEN…
<= Less or equal to IF a <= 15 THEN
> Greater than IF a > 15 THEN…
>= Greater or equal to IF a >= 15 THEN…

LOGICAL OPERATORS The type logical can have only two different values: true and false. These are variables
that can only take Boolean values. Logical variables can be operated upon by logical operators. These are:

OPERATOR MEANING
OR Logical OR
AND Logical AND
NOT Complement/Negation

QBASIC EXPRESSIONS AND STATEMENTS


An expression is a combination of symbols that forms a valid unit for evaluation or computation. Examples
include
3
a −7 b
X=
3 b+ √ d
The mathematical expression above can be express in QBASIC assignment statement as follow;

X = (a^3 – 7*b^2)/(3*b + d^(1/2))

INPUT/OUTPUT STATEMENTS
Data can be transferred into the program using input statement and the results be communicated to the
user or the outside world using the output statement. In programming, these statements are generally
known as input/output statements or simply i/o statements.
INPUT: This statement allows the user to enter a value for the variable while running the program. A
question mark (?) appears on the output screen waiting for the user to enter a relevant data and then press
enter key. Once the Return key or Enter key is pressed the data is stored in the variable.

SYNTAX : INPUT < VARIABLE >

Examples include;

11
Input A…… Enter Numeric constant

Input “Enter name:” ;N$…. Giving relevant message to avoid erroneous data input

OUTPUT STATEMENTS: This statement displays the results or the required output of a QBASIC program on
the screen for the user to visualize. It is implemented using the PRINT statement with the syntax as shown
below;

PRINT < VARIABLE >

Examples include;

a) PRINT “My name is Nick.”


Type the bolded text into QBasic and press F5 to run the program. On the screen you’ll see: My name is
Nick.
Note: you must put the text in quotes, like this – “text”. The text in quotes is called a string. If you put
the PRINT alone, without any text, it will just put an empty line. PRINT can also put numbers on the
screen.
b) PRINT 57 will show the number 57. This command is useful for displaying the result of mathematical
calculations. But for calculations, as well as for other things in the program, you need to use variables.
c) Given an assignment statement; a = 35; the print statement below can output the value of a on the
screen: PRINT a
d) Suppose a$= “welcome to the computing world”, PRINT a$ can display welcome to the computing world
on the computer screen
e) The PRINT command can print more than one string on the line. To do this, put the ; sign between the
variables. For example, you have two variables – name$ and age, where name$ contains Doowuese, and
age contains the number 12. Then, to print both name and age, you type: PRINT “Her name is”; name$;
“. She’s age: ”; age What you see on the screen when you run the program will look like this:
Her name is Doowuese. She’s age: 12
Or, you can type a program statement like this:
PRINT “Her name is :”; name$
PRINT “She’s age”;
age The result is:
Her name is Doowuese
She’s age 12
f) Print with Semi-Colon (;) Semi-colon placed after the message to be displayed, leaves no space between
two messages. E.g., Print “This is an example”;” of QBasic program” output: This is an example of QBasic
program
g) Print with Comma (,): The screen of the computer is made of 80 columns and 40 rows. The columns are
divided into five (5) zones of 14 columns each. Comma placed after the message prints the message zone
wise on the screen.

THE REM STATEMENT


REM: It stands for Remark. It gives an explanation of the program or of the statements in the program
thereby making the program more understandable to the reader. It is used for making comments and hence
the computer does not execute this statement and whatever is written after REM is ignored by the
interpreter. REM can be used anywhere and many times in a program. E.g. REM: this program introduces
chemical engineering students to QBASIC programs

THE END STATEMENT


END: This command is usually given at the end of the program. Statements written after end are not
executed since the program terminates execution on reading this command.

THE CLS STATEMENT


CLS: This command is used to clear the screen. It is written at the beginning of a program.

12
THE DELETE STATEMENT
DELETE: To delete a line number in a program. e.g. Delete 10 will delete line number 10 Delete 30-50 will
delete all line numbers between 30 to 50.

THE GOTO STATEMENT


Quite often you don’t want the program to run exactly in the order you put the lines, from the first to the
last. Sometimes you want the program to jump to a particular line. You can use GOTO to jump both forward
and backward to any line you want.
The syntax for GOTO statement is given below;

GOTO n where N is the label.

A label is a line number. Generally, statements in QBASIC are assigned serial number for referencing. Always
remember to include a label in a GOTO statement. You can have more than one label, but in that case they
should be different.

READ AND DATA STATEMENTS


READ and DATA statements offer an alternative method of assigning values to variables. Below are two ways
of assigning the variable X the value 2.
Method 1 : X = 2 Method 2 : READ X

DATA 2

Here are four ways of assigning X the value 2 and Y the value 3:

X=2 READ X, Y READ X READ X, Y

Y=3 DATA 2, 3 READ Y DATA 2

DATA 2, 3 DATA 3

When Basic comes to a READ statement containing a list of variables, it looks for a DATA statement
containing a list of values. It reads the data values one at a time, in the order listed and beginning with the
first DATA statement in the program. A DATA statement may appear anywhere in the program - Basic will
find it. Some programmers place all DATA statements at the beginning of the program, some at the end,
while others like to place a DATA statement right after the READ statement referring to it. All READ and
DATA statements may refer to strings as well as numerical variables. Items in READ and DATA statements are
separated by commas.

Example :

READ student$, class$, age, weight, homecity$

DATA Joe Smith, junior, 22, 154, "Honolulu, Hawaii"

In a DATA statement it is optional whether or not you put quotation marks around a string; however, if the
string contains punctuation marks then you might need quotation marks to avoid ambiguity. If one typed
just Honolulu, Hawaii in the above DATA statement, then Basic would interpret Honolulu and Hawaii as two
different strings.

If a DATA statement is too long for the screen, divide it into two statements, as below:

DATA Ann Ames, Betsy Bates, Cindy Crim, Diana Dees, Eve Evans

DATA Freda Finley, Greta Garbo, Hilary Hill, Inez Ingall, Jan Joplin

Be certain that data types in your DATA statements match variable types in your READ statements. The
sequence

13
READ A$, B

DATA horse, buggy

produces a "Syntax error" message, because "B" is a numeric variable but "buggy" is a string.

THE IF…THEN STATEMENT

This is a logical statement that is vital for altering the sequential flow of a program. The syntax for IF…THEN
statement is given below;

IF (logical expressions) THEN stmt

where stmt represents a QBASIC statement.

Alternatively, we can express the IF…THEN statement as a block viz;

IF (logical expressions) THEN

Stmt(s)

ENDIF

Stmt(s) represent QBASIC statement(s)

If the logical expression or argument is true, the interpreter executes the statement(s) immediately after the
THEN keyword. If the argument is not TRUE, then the QBasic bypasses this line(s) and goes to the next.

Example: IF a = 15 THEN PRINT "OK"

If the argument is not true (if a is not equal to 15), QBasic bypasses this line and goes to the next. In some cases,
you can use the ELSE command, which tells QBasic exactly what to do if the argument is not true.

THE IF…THEN…ELSE STATEMENT

This statement has the following syntax;

IF (logical expressions) THEN stmtELSE stmt

Or

IF (logical expressions) THEN

Stmt(s)

ELSE

Stmt(s)

ENDIF

The ELSE command tells QBasic exactly what to do if the logical expression is not true.

You can make QBasic to execute more than one command if the argument is true. To do this, put those
commands after IF…THEN and divide them with : symbol.

Example: IF a = 15 THEN PRINT "OK": GOTO 5

This example means that if a equals to 15, QBasic will first print OK and then will go to the line labelled 5

LOOPING STATEMENTS

14
When a set of instructions are repeatedly executed a fixed number of times it is termed as Loop. A loop simply
means iteration or a repetition.
To make interesting and efficient programs, you can make QBasic to execute a part of a program more than
once. This is called looping, when QBasic goes through a part of a program over and over again. This can be done
with the GOTO command, but there are some good and more efficient ways to loop the program rather using
GOTO statements. One of them is FOR...NEXT command. Loops can be implemented using counters to keep
track of the number of repetitions to done. When using Counters, we have to follow the following points:

1. Initialize the counter

2. Increment or Decrement the counter

3. Check for the maximum limit

Example of a counter includes; suppose the variable I is initialize to zero, a counter will be implemented as
follows:

i=i+1

The term Counter is used to describe a variable that we use to count up;

 how many things that we have


 how many times something is repeated

NOTE: counters are most useful in loops and if statements

FOR…NEXT LOOP

This command allows you to execute a part of a program a certain number of times. It has the syntax as shown
below:

FOR var = x TO y [STEP z]

Program statements…

NEXT [var]

Where

• var is a variable. It is a counter and is called the ‘Control Variable’.

• x is the start value

• y is the final or ending value

• x and y are numeric values

• var is assigned all values starting with x terminating with y in steps of z

NB: The [step] size at the loop header is optional. If STEP is not given then BASIC assumes the increment to be 1.
Also, var increments or decrements depending on whether the number specified in STEP is positive or negative.

Example include;

FOR a = 1 TO 5

PRINT "This is loop number"; a

NEXT a

This will print:

This is loop number 1

This is loop number 2

15
This is loop number 3

This is loop number 4

This is loop number 5

The STEP command can be implored as shown below. This will tell QBasic how to count from one number to
another:

FOR j = 0 TO 12 STEP 2

statements….

NEXT j

The above loop will count in two’s: 0, 2, 4, 6, 8, 10, 12.

Examples include:

1.Program to print numbers 10 to 15 using For…Next loop

10 Let N = 15

20 FOR M = 10 TO N

30 Print M;

40 Next M

Output as displayed on

screen:

10 11 12 13 14 15

2. Program to print numbers 40 to 50 in reverse order using For…Next loop

10 FOR A = 50 TO 40 STEP –1

20 Print A;

30 Next A

Output as displayed on the screen:50 49 48 47 46 45 44 43 42 41 40

3.Program to print first 10 multiple of any number input

10 Input “Enter any number “,n

20 for I= 1 to 10

30 Print n; ”x” ;I “=” n* i

40 next

Output :

10 x 1 = 10

16
10 x 2 = 20

10 x 3 = 30

10 x 4 = 40

…….

WHILE...WEND
The WHILE...WEND commands continue a loop until a specified expression is false.
To use WHILE...WEND:

1. Place an expression after WHILE

2. Enter a list of commands

3. Place WEND at the end

The general syntax for the WHILE…WEND loop is as follow;

WHILE [logical expression]

Stmt-1

Stmt-2

Stmt-n

WEND

Example include;

5 x = 10

10 WHILE x < 15

15 PRINT x

20 x = x + 1

25 WEND

Recall: x=x+1 is a counter

Output :

10

11

12

13

14

17
THE DO… LOOP
This loop uses both WHILE
and UNTIL keywords.

With DO...LOOP you can:

1. Loop until an expression is true

2. Loop at least one time regardless of whether the expression is true or not.

To use DO...LOOP:

1. Specify whether the loop continues "while" the expression is true or"until" the expression is true,
using the WHILE and UNTIL statements, respectively.

2. Place an expression after WHILE/UNTIL

3. Enter a list of commands

4. Place LOOP at the end

The syntax for the Do…WHILE loop is given below;

DO WHILE [logical expression]

Stmt-1

Stmt-2

Stmt-n

LOOP

The following uses the WHILE statement:

x = 10

DO WHILE x < 15

PRINT x

x=x+1

LOOP

The syntax for DO…UNTIL loop is given below;

DO UNTIL [logical expression]

Stmt-1

Stmt-2

Stmt-n

LOOP

This program uses the UNTIL statement:

x = 10

DO UNTIL x = 15

PRINT x
18
x=x+1

LOOP

The both output:

10

11

12

13

14

If you place the expression at the end of the loop instead, the program goes through the loop at least once.

x = 32

DO

PRINT x

x=x+1

LOOP WHILE x < 5

This is the output because the loop was only gone through one time: 32

The Sample program for a DO WHILE Loop

*** This program adds a list of positive integers. ***

CLS

Sum = 0

INPUT "Enter the first number (-l to quit): ", Number

DO WHILE Number <> -1

Sum = Sum + Number

INPUT "Enter the next number (quit if -1): ", Number

LOOP

PRINT "The sum is"; Sum

END

Program Output

Enter the first number (quit if -1): 24

Enter the next number (quit if -1): 18

Enter the next number (quit if -1): 91

Enter the next number (quit if -1): -1

The sum is 133

Notice that Sum is set to zero immediately before the loop is entered. Technically, this statement is not needed.
QBasic automatically sets the values of numeric variables to zero and string variables to the null (empty) string
before execution begins. However, it is good programming practice to initialize variables yourself, rather than
depending on "default" initializations.
19
Nested loops:
You can put a loop inside of another loop in a structure called nested loops. This is done by placing one
For...Next loop within another. Each loop MUST have a unique variable name as its loop counter.
Nested loop example:

For I = 1 To 10

For J = 1 To 10

For K = 1 To 10

Statement(s)

Next K

Next J

Next I

NB: Remember that nested loops must be bracketed in LIFO order. That means that the inner-most loop ends
first and the outermost loop ends last.

The EXIT Statement


Occasionally, it may be necessary to exit a loop prematurely. Most commonly, this occurs if an error condition is
encountered; for example, if invalid data has been read. The EXIT statement can be placed anywhere in a DO...
LOOP and causes execution to be immediately transferred to the first statement after LOOP For example, the
following program segment is supposed to read the names of 12 voters. However, if a value of less than 18 is
read for Age, an error message is displayed and the loop terminates.
Rem Read and display names of 12 voters. ***

DO WHILE Count <= 12

READ Voter, Age

IF Age < 18 THEN

PRINT

PRINT Voter ; " is not eligible to vote."

EXIT DO

END IF

PRINT Voter$

Count = Count + 1

READ Voter$, Age

LOOP

Rem Data statements

DATA Santana, 18, Matthews, 44, Ericson, 17, Ling, 29

END

If the EXIT DO statement is executed, control transfers to the first statement after LOOP However, this
statement is executed only if an invalid value for Age is encountered. The EXIT statement can he used with other
structures, such as SUB procedures. The statement EXIT SUB allows control to be transferred immediately back
to the calling program. However, a word of warning: The EXIT statement can lead to program errors. It also
makes program logic more difficult to follow. Therefore, it is best to avoid its use unless absolutely necessary.
20
Counters vs Accumulators
The term Accumulator is used to describe a variable that is being used to total up a bunch of numbers.To use a
variable as an accumulator, you must follow these two steps:
1. Set the variable that will be used as an accumulator to a starting value (usually you will start theaccumulator
at '0' [zero] )

2. Next add something to what is already stored in the accumulator

(for example: Accumulator = Accumulator + someNumber)

NOTE: Accumulators are often found in loops because they repeat the process of "accumulating" numbers.

In the QBASIC code shown below, the variable named "TOTAL" is used as an accumulator.

LET TOTAL = 0.0

LET AVG = 0.0

CLS

PRINT "Please enter five marks"

FOR I = 1 to 5

INPUT "Enter mark: "; mark

TOTAL = TOTAL + mark

NEXT I

AVG = TOTAL / 5

PRINT "The total of the marks is ";TOTAL

PRINT "The average of the marks is ";AVG

END

ARRAYS

An array is a list of variables of the same type. Arrays are useful for organizing multiple variables. To create an
array, use the DIM (dimension) command. The general syntax for declaring array is: DIM varname (arraysize),
Where varname is the array name; arraysize is the size of the array

The following example does not use arrays:

a=2

b=4

c=6

d=8

e = 10

PRINT a, b, c, d, e

Output:

2 4 6 8 10

This uses an array called vars, which contains 5 variables:

DIM vars(5)

' Each of these are separate variables:


21
vars(1) = 2

vars(2) = 4

vars(3) = 6

vars(4) = 8

vars(5) = 10

PRINT vars(1), vars(2), vars(3), vars(4), vars(5)

Output:

2 4 6 8 10

The above program can also be written like this:

DIM vars(5)

FOR x = 1 to 5

vars(x) = x * 2

NEXT

FOR x = 1 to 5

PRINT vars(x),

NEXT

Output:

2 4 6 8 10

Unsolved Program on LET and PRINT statements:

1. Write a program in QBASIC to greet your friend on the occasion of New Year by using PRINT statement. The
output of the program is shown as:

Season's Greeting
Best Wishes for
A Happy and Prosperous New Year
From:
Name

Ans:
CLS
LET A$= “Season's Greeting”

LET B$= “Best Wishes for"


LET C$= “A Happy and Prosperous New Year"
LET D$= “Rourkela"
LET E$= “SANIYA RANA"
PRINT “Season's Greeting:"; A$
PRINT “Best Wishes for:";B$

22
PRINT “A Happy and Prosperous New Year:";C$
PRINT “From:";D$
PRINT “Name:";E$

23
2. There are 28 boys and 22 girls in your class. Write a program in QBASIC to fine the percentage of boys and
girls in the class.
Ans:
CLS
LET B=28
LET G=22
LET T=50
LET P1=B/T*100
LET P2=G/T*100
PRINT P1, P2
END

3. The base and height of a triangle are 15 cm and 10 cm respectively. Write a program in QBASIC to calculate
the area of the triangle.
Ans:
CLS
LET B=15cm
LET H=10cm
LET A= ^*B*H
PRINT "Area="; A
END

4. A Salesman sold 14 chairs at the rate of 275/- each and 3 tables at the rate of 650/-. Write a program in
QBASIC to calculate the total sale.
Ans:
CLS
LET C= 14 *275
LET D=3*650
LET T=C+D
PRINT “Chair, Table =”; C, D
Print "Total sale =”; T

24
5. Write a Program in QBASIC to calculate the area and circumference of a circle of the radius 14 cm.
Ans:
CLS
LET r= 14 CM
LET A= 22/7 *r*r
LET C= 2*22/7*r
PRINT "Area:"; A
PRINT "Circumference:"; C
END

Home Assignment
1. Write a program in QBASIC to find the value of the given expression when a=10, b=5, c=2.
a. aA2 +bA3+cA4
CLS
LET a=10
LET b=5
LET c= 2
LET D=a*a +b*b*b+c*c*c*c
PRINT D
END
b. ( a + b) A2
CLS
LET a=10
LET b=5
LET c= 2
LET D= (a + b) A2
PRINT D
END
c. aA2 + bA2
CLS
LET a=10
LET b=5
LET c= 2

25
LET D= aA2 + bA2
PRINT D
END

d. ( a -b +c )A2
CLS
LET a=10
LET b=5
LET c= 2
LET D= ( a -b +c ”2
PRINT D
END

2. In a class of 60 students, 90% are present. Write a program in QBASIC to calculate the number of students
present and absent.
Ans:
CLS
LET S= 60
LET P=90/100*60
LET A=60-P
PRINT “Present =”; P
PRINT "Absent =”; A
END

3. The rate of petrol is 47.60/- per litre. You paid 250/- to the pump attendant and asked for 5litres of petrol to be
filled in the tank. Write a Program in QBASIC to calculate the cost of petrol and the amount of money refunded.
Ans:
CLS
LET C=47.60*5
LET R= 250-C
PRINT "Cost of petrol=”; C
PRINT "Refund money =”; R

26
4. In a book fair, you purchased the following books:
Harry Potter Books : 950/-
English Dictionary : 1200/-
Encyclopedia : 1600/-
You gave an amount of 4000/- to the shopkeeper. Write a program in QBASIC to calculate the total amount
to
Be paid to the shopkeeper and the money refunded by him.
Ans:
CLS
LET H=950
LET E=1200
LET C=1600
LET T= H+E+C
LET R= 4000-T
PRINT “Harry Potter Books:”; H
PRINT "English Dictionary:”; E
PRINT "Encyclopedia:” ; C
PRINT "Total Cost:”; T
PRINT "Refund Money:”; R
END
5. 'LEXPO' announces 25% discount on all leather items. You purchased a leather bag that costs 660/- and a
belt priced 160/-. Write a program in QBASIC to calculate the amount to be paid to the shopkeeper.
Ans:
CLS
LET B=660
LET C=160
LET T=B+C
LET D= T*25/100
LET A=T-D
PRINT "Leather Bag:”; B
PRINT "Belt:”; C
PRINT "Total:”; T
PRINT "Discount:”; D
PRINT "Amount:” ; A

27
INPUT STATEMENT
EXERCISES
I. State whether the following statements are True/False:

1. INPUT N$ will accept a string constant. True


2. A question mark is displayed on the screen while executing an INPUT statement. True
3. INPUT A, B, C will accept only one numeric constant. False
4. A numeric variable with the INPUT statement responds to a string constant. False
5. A message may be given along with an INPUT statement to make the program
user-friendly. False
6. Numeric or alphanumeric constants should not be used along with the INPUT
Statement. False
7. INPUT N$, M will accept one alphanumeric constant and one numeric constant. True
8. INPUT statement accepts the data value during execution of the program. True
9. There is no difference between LET and INPUT statement in QBASIC. False
10. INPUT "Information Technology “is a valid statement. False

Short Answer Questions:

1. What is the purpose of using INPUT statement in a program?


Ans: with the use of INPUT statement, you can enter any data to a numeric variable or an alphanumeric variable
at the time of execution. In other words, you can make your program user-friendly.

2. How does LET statement differ from an INPUT statement?


Ans: with the use of INPUT statement, you can enter any data to a numeric variable or an alphanumeric variable
at the time of execution. In other words, you can make your program user-friendly, which cannot be done by LET
statement.

3. Write down the syntax of:


a. INPUT statement with a numeric variable

28
INPUT<Numeric variable>
Example: INPUT N

b. INPUT statement with an alphanumeric variable


INPUT < Alphanumeric variable>
Example: INPUT A$

II. BASIC Programming:

1. Write a program in QBASIC to make a name striker which includes your name, class, roll no., subject and
school using INPUT statement. Display the output in the given format:

Ans:

CLS

INPUT “Enter name”; N$

INPUT "Enter class”; CL$

INPUT "Enter roll number”; R

INPUT "Enter Subject”; S$

INPUT "Enter School”; SCH$

PRINT "Name:”; N$

PRINT "Class:”; CL$

PRINT "Roll No:”; R

PRINT "Subject:”; S$

29
PRINT "School:”; SCH$

30
2. Write a program in QB ASIC format to accept the length of a rod in millimetres and express the same in centimetres
and metres.
Ans:
CLS
INPUT "Enter length of the rod in millimetres"; M
C=M/10
S= M/1000
PRINT "Length of the rod in centimetre="; C
PRINT "Length of the rod in meter ="; S
END

3. Write a program in QB ASIC format to print the total amount paid to the shopkeeper for purchasing the following
items:
Number of exercise books =10
Number of brown paper rolls=4
Ans:
CLS
INPUT "Enter the number of exercise book"; E
INPUT "Enter the number of brown paper rolls"; R
T=E+R
PRINT "Total=";T
END

4. Write a program in QB ASIC to find the value of the given expressions after taking a suitable v a lue of a and b from
the console:

i. aA2+bA2
Ans:
CLS
INPUT "Enter the value of a and b"; a, b
A=aA2+bA2
PRINT "The valueof A="; A
END

31
OUTPUT: Enter a=2, b=2
A= 2A2 +2A2
A=8

ii. a+b
ab
CLS
INPUT “Enter the value of a and b”; a, b
A= a+b
B=ab
C=A/B
PRINT "Value of A =”; A
PRINT "Value of B=”; B
PRINT "Value of C=”; C
END

OUTPUT: Enter a=2, b=2


A= 4, B= 4, C= 1

5. You want to calculate the total runs made by Sachin Tendulkar only in terms of centuries and halfcenturies in test
matches. Write a program in the QBASIC format taking the numbers of centuries and half-centuries as input.
Display the total runs made by Sachin in Centuries and half-centuries separately.
Ans:
CLS
INPUT "Enter the numbers of Centuries”; C
INPUT "Enter the number of Half-Centuries”; H
T1=C*100
T2=H*50
PRINT "Total runs made by Sachin Tendulkar in centuries=”; T1
PRINT "Total runs made by Sachin Tendulkar in Half-centuries=”; T2
In an examination, 20% students failed in English and 30% failed in maths. Write a program in
32
QB ASIC format to find the total number of students who failed in both the subjects taking the total number of
students in the class as input.
Ans:
CLS
INPUTN
E= (20/100)*N
M= (30/100)*N
T=E+M
PRINT "Total=";T
END

6. Write a program in QB ASIC format to find the value of's' in the given equations, taking the suitable value of '๙, 'v'
and 'a' as input.

S= vA2-uA2
2a
Ans:
CLS
INPUT "Enter the value of"; u, v, a
S= v*v-u*u
D= 2*a
E= S/D
PRINT "The value of:" S
END

7. You purchased a Computer textbook and an Oxford dictionary. The shopkeeper allows 10% discount on the
textbook and 20% discount on the dictionary. Write a program in QB ASIC format to calculate the total discount and
the amount to be paid to the shopkeeper, taking price of the books as input.
Ans:
CLS
INPUT "Enter the price of the Computer"; Pl INPUT "Enter the price of the dictionary"; P2 Dl=10/100*Pl

33
D2=20/100*P2
T=D1+D2
A1=P1-D1
A2=P2-D2
A=A1+A2
PRINT “The Total discount:"; T
PRINT “The amount=" ; A
END

34

You might also like