Вы находитесь на странице: 1из 140

CHAPTER ONE

UNDERSTANDING SOFTWARE

Definition

Software is another name for computer program just as agenda is another name for a
meeting program and recipe for a cooking program.

Technically speaking however, software is a sequence of instructions coded in a


programming language which the computer hardware executes in order to carry
out its tasks. In other words the software states what task to be done and how,
whereas the hardware takes actions based on the stated instructions. Software and
hardware are therefore complementary as well as interdependent on each other.

Qualities of Good Software

The computer by nature is not intelligent being made up bunch of wires and electronic
devices that are themselves not intelligent. The intelligence of the computer
emanates from the encoded software. This is why the computer is commonly said
to be garbage-in, garbage-out meaning that whatever you tell it to do via the
software is what it will do without thinking. So if the software is illogical the
computer also will be illogical. Good quality software therefore is not negotiable
but must be pursued with every skill and attention.

The qualities of good software are outlined and discussed below.

i. Utility

Software must be properly written to effectively address the need it is desired


to fulfill, no more no less.

Reliability
Software is said to be reliable if it always produces the correct result. This will
depend on the conceptual correctness of algorithms, and minimization of
programming mistakes called bugs.

Robustness
Software is robust if it is able to withstand crash in the event of problems due
to programmer or user error.

Efficiency

1
Software is said to be efficient if it consumes a small amount of system
resources such as processor time, memory space, network bandwidth, slow
devices such as disks, and to some extent user interaction.

Efficiency also includes correct disposal of system resources, such as cleaning


up temporary files, and lack of memory leaks.

Usability
This refers to the ease of use of software for its intended purpose. Software
which users find it too difficult to use is not of a good quality.

Portability
Software is said to be portable if it runs on a wide range of computer hardware
and operating system platforms.

Maintainability
Software should be readable and clear enough to its present and future
developers to make improvements or customizations, fix bugs and security
holes, or adapt it to new environments.

In conclusion it is pertinent to point out that quality software is not a product of


chance but that of a good programming skill and habit. Therefore good
programming skill and habit should be cultivated from the onset of learning how
to program. This is the whole gamut of this book: to teach both experienced and
upcoming programmers good programming skill and habit so that our software
market will be flooded with nothing less than quality software that causes the
hardware to do the right things the right way.

Types of Software

Practical computer systems divide software systems into three major classes: system
software, application software and programming software.

System Software

System software is a computer program that is designed to service and control the
operations of the computer system. Thus system software does not therefore
service any user needs but creates the enabling environment for the computer
system to carry out its functions efficiently.

Basically, we have three types of system software. These include: operating system,
device drivers, and diagnostic tools (or utility software).

2
Operating System

The operating system is the computer manager software which controls the allocation
and usage of hardware resources (such as memory, CPU time, disk space,
peripheral devices) and functions as an interface between the user, application
programs, and the hardware

Examples of operating systems are MS DOS 6.2, Windows 98, Windows XP, Vista,
Windows 7, OS/2, UNIX and LINUX.

The basic functions of the operating system include:

Computer management
The operating system allows the user to install new hardware, applications,
files, and customize the interface. It manages multiple users of the system, and
grants them access to common tools such as anti-virus and data backup
utilities.

Hardware management
The operating system provides shared access to computer resources, such as
CPU, memory, disk drives, and peripherals to applications software.

File management
It provides an interface to the user to organize data on the computer’s storage
devices, using files, directories, and disks.

Network access
It helps the computer to integrate with other computer systems, such as a
network server or workgroup, and connect with public networks, such as the
internet.

Integration of data
It enables the user to work with different software applications at the same
time. Thus a user could open different files and applications at the same time
(multi-tasking), and/or transfer data from a file of one type to one of another
type (object linking and embedding, (OLE) or automation).

Device Drivers
Peripheral devices such as CD-ROMs, disk drives, keyboards, mice, modems,
monitors and printers will never communicate with a computer system just by being
connected physically to the computer. The driver of the device must be installed in the
computer first before such communication can take place. A driver therefore is
interface software which enables a device to integrate and communicate with a
computer system.

3
It is pertinent to know that many devices have their drivers bundled together with the
operating systems. This is why such devices are installed automatically on connecting
them to the computer the first time. Once installed a device can always connect and
communicate with the system without any subsequent reinstallation of its driver. In
other words, a driver installation is needed once in a system.

Diagnostic Software
Diagnostic software usually refers to software that solves narrowly focused computer
problems or those related to computer system maintenance. It usually performs
routine tasks and support operations.

Examples of Diagnostic software include: anti-virus, defragmenting software,


formatting software, etc.

Application Software

Application software is a computer program designed to carry out some tasks such as
word processing, program design, and database management, directly for a user.
Such software usually produces information.

Types of application software include:

i. Word Processors

Examples: MS Word, WordPerfect

ii. Text Editors

Examples: Notepad, emacs, vi.

iii. Desktop Publishing Software


Example: Adobe PageMaker

iv. Spreadsheets
Examples: Excel, QuattroPro, SPSS

v. Databases
Examples: Access, Paradox, MySQL, Oracle

vi. Presentation Graphics


Example: PowerPoint

vii. Desktop Information Management Systems


Example: Outlook
4
viii. Communication and E-Mail Software
Example: Outlook

ix. Media Players


Examples: Windows Media Player. Power DVD.

As programmers much of the programs we shall be writing will be application


software.

Programming Software

The last kind of software we shall consider in this book is the programming software.
It is the software tool that we use to create the other kinds of software and is
normally referred to as programming language. A programming language is
therefore a set of notations and rules for the precise expression of computer
programs. A variety of different programming languages have evolved over time.
Each of these languages has its own unique syntax and semantics.

Programming languages are often categorized as either high-level or low-level. Low-


level programming languages are those that are closer to machine language, while
high-level programming languages are those that are closer to human language.

Machine Language

Machine language is a low-level programming language which expresses computer


programs in binary numbers, i.e. zeros and ones. It is the native language of
computer meaning that the computer can understand it naturally without any need
of interpretation. Machine language is also commonly referred to as machine
code.

Consider a program instruction which adds two numbers together and stores the result
in memory. The Intel machine code for the program will read:

00000001 11011000

This is quite cryptic and difficult to memorize. Programmers therefore find it very
difficult, if not impossible, to write programs in machine language. First, this is
because a programmer cannot memorize the thousands of binary instructions that
make up the machine language. This is even made more difficult for the fact that
machine language is processor specific, meaning that every processor has its own
native machine language.

5
The second reason why programmers do not program in machine language is because
machine languages, being made up of series of 0s and 1s, are prone to error and
difficult to debug.

Assembly Language

Assembly language is another type of low-level programming language which uses


two-, three-, or four-letter mnemonics to express computer programs. A
mnemonic is any device that makes information easier to memorize. It was
developed in 1952 by American mathematician, Grace Murray Hopper to
overcome the problems associated with writing programs in machine code.

Each statement in assembly language usually corresponds directly to a single machine


code instruction. Assembly language is thus also processor specific just as the
machine language.

Consider once again the program instruction which adds two numbers together and
stores the result in memory. The equivalent Intel Assembler instruction will be
written as follows:

Add ax, a

This means add the contents at symbolic address a to the ax register. Comparing this
assembly language code to the equivalent machine code (00000001 11011000),
we see clearly that it is simpler to write and memorize assembly language code
than machine code.

Note however that assembly language is not understood directly by computer.


Therefore for the computer to understand it, the assembly language code must
first of all be translated to the machine language equivalence. This is done using a
program called assembler. Example of assemblers includes BAL (Basic
AssembLer), FAP (FORTRAN Assembly Program), and MASM (Microsoft
Macro Assembler).

The major reasons why we might consider assembly language better suited for
programming include:

Speed
Programs written in assembly language usually run faster than those generated
by a compiler.

Control

6
Use of assembly language lets a programmer interact directly with the
hardware (processor, memory, display, and input/output ports).

Simplicity
Assembly language mnemonics are very close to human natural language. For
instance, ADD stands for add, MOV stands for move, CMP for compare, JMP
for jump, etc. This therefore makes assembly language instructions simple and
short unlike high-level programming language instructions.

High-Level Programming Language

High-level programming languages are those computer languages which use


relatively sophisticated sets of statements utilizing words from human language.

They are more similar to normal human languages than assembly or machine
languages and are therefore simpler and faster to use for writing large or
complicated computer programs.

For example, our simple program instruction to add two numbers together and store
the result in memory can simply be written in any high-level programming
language as:

A=A+B

The following is a table of some popular high-level programming languages in use in


the world today. A complete list of most of the programming languages known at the
time of writing this book is given in Appendix A.

Table 1: High-Level Programming Languages

Language Origin of Name Year Uses/Comments

ADA Augusta ADA Byron (Lady 1979 Derived from Pascal, used primarily by the
Lovelace) military.
ALGOL ALGOrithmic Language 1960 First structured procedural programming
language, used mainly for solving math
problems.
APL A Programming Language 1961 Interpreted language using a large set of
special symbols and terse syntax. Used
primarily by mathematicians.
BASIC Beginners All-Purpose 1965 Very popular high-level programming
Symbolic Instruction Code language, frequently used by beginning
programmers.

7
Language Origin of Name Year Uses/Comments
C Predecessor was Bell 1972 Compiled, structured, programming
Laboratory's 1972 B language commonly used in many
Programming Language workplaces because its programs are easy to
transfer between different types of
computers.
C++ Advanced version of C. 1985 C++ is used in numerous fields, such as
Developed at ATT Bell accounting and finance systems, and
Labs. computer-aided design. Supports object-
oriented programming.
COBOL COmmon Business- 1959 English-like programming language,
Oriented Language emphasizes data structures. Widely used,
especially in businesses.
FORTH FOuRTH-Generation 1970 Interpreted, structured language, easily
language (4 GL) extended. Provides high functionality in
limited space.
Fortran FORmula TRANslation 1954 Initially designed for scientific and
engineering uses, a high-level, compiled
language now used in many fields.
Introduced several concepts such as
variables, conditional statements, and
separately compiled subroutines.
HTML HyperText Markup 1989 Designed for publishing hypertext on the
Language Internet.
JAVA Sun Microsystems 1990 Originally developed for use in set-top
developers drank a lot of boxes, transitioned to the World Wide Web
coffee when coding for this. in 1994.
LISP LISt Processing 1960 A list-oriented programming language,
mainly used to manipulate lists of data.
Interpreted language, often used in research,
generally considered the 'standard' language
for Artificial Intelligence (AI) projects.
LOGO Derived from Greek logos, 1968 Programming language often used with
meaning word children. Features a simple drawing
environment and several higher-level
features from LISP. Primarily educational.
Modula-2 MODULAr Language, 1980 Language that emphasizes modular
designed as secondary programming. High-level language based on
phase of Pascal (Niklaus Pascal, characterized by lack of standard
Wirth devised both) functions and procedures.
Pascal Blaise PASCAL, 1971 Compiled, structured language, based on
mathematician and inventor ALGOL. Adds data types and structures
of first computing device while simplifying syntax. Like C language,
it is a standard development language for
microcomputers.
PERL Practical Extraction and 1988 It is a text-processing language that looks

8
Language Origin of Name Year Uses/Comments
Report Language like a combination of C and several Unix
text processing utilities.
PILOT Programmed Inquiry, 1969 Programming language used primarily to
Language Or Teaching create applications for computer-aided
instruction. Contains very little syntax.
PL/1 Programming Language 1964 Designed to combine the key features of
One Fortran, COBOL, and ALGOL, a complex
programming language. Compiled,
structured language capable of error
handling and multitasking, used in some
academic and research environments.
SGML Standard Generalized 1986 Designed as a metalanguage, it is used as an
Markup Language international standard for the description of
marked-up electronic text.
SQL Structured Query Language 1986 Designed to be used for creating complex
databases and accessing data in a relational
database.
VB Visual Basic 1990 Sometimes called the Rapid Applications
Development system, is used to build
applications quickly.
XML Extensible Markup 1977 Used for creating arbitrarily-structured
Language documents and Web pages; it is commonly
associated with the Internet.

High-Level Language Translators

High-level language programs like assembly language programs cannot be understood


directly by a computer system. The program must be translated to machine
language first before the computer can understand it.

There are two types of translators that can be used for high-level language programs.
These include the compiler and the interpreter. The two use different approaches
to carry out the process of language translation. While a compiler takes the whole
high-level language program and converts it into an object code (the machine
code) which the computer then executes. So to run a compiled program, you run
the object code.

This is analogous to a French book which has been translated into English language.
If you are literate in English language only, it means that to read this book, you
will have to do so with the English version rather than the French version.

High-level languages such as C, C++, FORTRAN, etc use compilers.

9
On the other hand, an interpreter is also a translator program which takes a source
code one line-of-instruction per time, and converts it into machine code for the
computer to execute before it goes to the next line-of-instruction. This means that
an interpreter does not produce an object code but enables a computer to merely
carry out instructions in the source code.

This can be likened to another French book without an English version. Since you do
not understand French, to read this book, you will need an interpreter who is
literate both in French and English. He/she reads the book a sentence at a time
and tells you what it says in English.

High-level languages such as BASIC and LISP use interpreters.

There are advantages for both compilers and interpreters. As a generalization,


compiled programs run faster but are slower to develop.

Compiled programs often run faster because the process of program translation is
done once and for all whereas translation is carried out every time an interpreted
program runs. This repeated translation causes delay in the execution of
interpreted programs.

It is however pertinent to note that interpreted programs are often written in smaller
time frame because the whole program does not need to be recompiled each time
a new feature is bug tested.

Programming Paradigms

High-level languages are commonly classified as either procedural, functional, object-


oriented, logic, etc. These classifications are called programming paradigms.
Paradigms refer to patterns or models of programming using high-level languages.
Some of the paradigms which have become popular among programmers are
explained as follows.

Procedural programming

The most common high-level languages in use today are procedural. In these
languages, one or more related blocks of statements that perform some complete
function are grouped together into a program module, or procedure, and given a
name such as procedure A. If the same sequence of operations is needed
elsewhere in the program, a simple statement such as a procedure call can be used
to refer back to the procedure.

10
In essence, a procedure is just a mini-program. A large program can be constructed by
grouping together procedures that perform different tasks.

Procedural languages allow programs to be shorter and easier for the computer to
read, but they require the programmer to design each procedure to be general
enough to be used in different situations.

Examples of procedural languages include: Ada , ALGOL, BASIC, BLISS, C,


COBOL, and Cobra.

Functional programming

Functional languages treat procedures as mathematical functions and allow them to be


processed like any other data in a program. This allows a much higher and more
rigorous level of program construction.

Functional languages also allow variables to be given values only once. This
simplifies programming by reducing the need to be concerned with the exact
order of statement execution, since a variable does not have to be re-declared, or
restated, each time it is used in a program statement.

Many of the ideas from functional languages have become key parts of many modern
procedural languages.

Examples of languages include: APL, Charity, Clean, Haskell, Hop, Kite, Lisp,
Mathematica, Poplog, and Spreadsheets.

Object-oriented programming

Object-oriented languages are outgrowths of functional languages. In object-oriented


languages, the code used to write the program and the data processed by the
program are bundled together into units called objects.

Objects also have certain functions associated with them, called methods. The
computer accesses an object through the use of one of the object’s methods. The
method performs some action to the data in the object and returns this value to
the computer.

Objects are further grouped into classes, which define the attributes and functions
objects must have.

Classes of objects can also be further grouped into hierarchies, in which objects of
one class can inherit methods from another class. The structure provided in

11
object-oriented languages makes them very useful for complicated programming
tasks.

The features which characterize objected-oriented programming are classes, objects,


methods, message passing, inheritance, encapsulation, information hiding, data
abstraction, and polymorphism.

Examples of objected-oriented programming include: Simula (the first object oriented


language), Smalltalk (pure object-oriented), X++, Modula-2, Java, and Common Lisp.

Logic Programming

Logic-based languages specify a set of attributes that a solution must have, rather than
a set of steps to obtain a solution. A logic program consists of sets of facts and if-
then rules, which specify how one set of facts may be deduced from others, for
example:

If the statement X is true, then the statement Y is false.

In the execution of such a program, an input statement can be logically deduced from
other statements in the program.

Many artificial intelligence programs are written in such languages. Examples


include: ALF, CLACL, Curry, Janus, Oz, Prolog, and ROOP

12
CHAPTER TWO

SOFTWARE DESING

Computer programming is the process of designing computer programs. This process


usually involves two phases which include:

Problem Solving Phase


Implementation Phase

13
CHAPTER THREE

ALGORITHM

According to Al Kho-war-iz-mi, a 9th century Persian mathematician, algorithm is an


ordered sequence of unambiguous and well-defined instructions that performs some
task and halts in finite time.

Simply put, an algorithm is a procedure for solving a problem in terms of the


instructions to be executed and the order in which those instructions are to be
executed.

When you develop an algorithm of the solution for a given task, your thought is
clarified and your understanding is enhanced before ever you attempt to write the
program.

The order of execution of an algorithm is determined by the following control


structures:

i. Sequence
Algorithmic instructions are executed one after the order starting with the first
instruction and ending with the last instruction.

ii. Decision (Condition)

14
This control structure is used to change the order of execution of instructions
by asking a true/false question and then selecting the next instruction for
execution based on the response.

iii. Iteration (Looping)

This control structure repeats the execution of a block of instructions for a


number of times as may be required.

You know that a task can be done in several ways. This means that a single task can
have several algorithms. However the algorithm that will be applied has to be chosen
based on the consideration of the speed and cost of execution of the algorithm.

Notations of Algorithm

Algorithms can be expressed in the following kinds of notations:

i. Natural language
Algorithms can be expressed with natural human language. However such
expressions of algorithms tend to be verbose and ambiguous, and so are rarely
used for complex or technical algorithms.

ii. Pseudocode
Pseudocode is a method of expressing algorithm using short English phrases
to make an ordered and logical listing of instructions. Pseudocode is often
used because algorithms expressed with pseudocode are rarely unambiguous.

iii. Flowcharts
Flowchart is a graphic representation of an algorithm, often used in the design
of programming to work out the logical flow of a program.

iv. Programming languages


Programming languages are used primarily to code algorithms in a form that a
computer can execute. Often they are also used to define or document
algorithms.

We shall not make use of the natural language to express computer algorithms for the
obvious reasons of verbosity and ambiguity which complicates it. We shall therefore
develop all our algorithms with either pseudocode or flowchart, or even both.
Thereafter we shall move into actual coding of programs using the BASIC language.

PSUEDOCODE

15
Recall that we defined algorithm as an ordered sequence of unambiguous and well-
defined instructions that performs some task and halts in finite time. Pseudocode is
one mode of expressing algorithm by using short English phrases to make a listing of
instructions.

It is important to note that the computer system executes program instructions one
after the other, starting with the first instruction and ending with the last instruction
(i.e. sequential execution). When program instructions are not arranged in the correct
order, we get illogical results. Consider for example, your preparation for school in
the morning: if you dress up first before bath, you will be bizarre and wet to school;
but if you bathe first before dress up, you will be both dry and smart to school. This
scenario paints a good picture to tell us how important it is to arrange our program
instructions in the correct order, also keeping in mind that the computer is garbage in
garbage out.

Why use Pseudocode?

The primary purpose of pseudocode is to help the programmer write code that is
logically correct and efficient. Pseudocode helps to clarify your thoughts, and
concentrate your mind on the logic of the program before you start to write any code.
One of the hardest temptations to resist in programming is the urge to start writing
code immediately without any algorithm. This is a bad programming habit. But
spending some time to think out carefully the best approaches to solve a given task is
good programming habit and which will eventually save you hours of time and
confusion later on.

Another reason to use pseudocode is that it turns into comments in your finished
program. This saves you much of the task of going back to a finished program to
insert comments.

How to Design Pseudocode

We shall adopt the following standards in our design of pseudocode:

• Number each instruction. This is to enforce the notion of an ordered sequence


of instructions

• Make each instruction unambiguous and effectively computable

• Ensure completeness. Add enough detail, leaving out nothing


• List all variables used at the end of the pseudocode. This will be useful when
translating pseudocode into a programming language.

16
Pseudo-code is best understood with examples. Each example below demonstrates
one of the control structures used in algorithms: sequence, decision, and iteration.

Example 1:

Design a pseudocode for a program which computes the final price of a product after
adding the value added tax (vat).

Solution:

1. get price of product


2. get vat rate
3. vat = price of product times vat rate
4. final price = price of product plus vat
5. display final price
6. end

Variables: price of product, vat rate, vat, final price.

In the solution given above, the instructions are numbered, rightly ordered,
unambiguous and effectively computable. Right order of instructions is indispensable
in programming. If you place number-2-instruction before number-1-instruction, the
algorithm will still be fine; but it cannot remain fine if you place number-2-instruction
after number- 3-instruction.

Also all variables used in the pseudocode are extracted and listed. This will be useful
when translating pseudocode into a programming language.

Example 2:

Design a pseudocode for a program which computes the weekly wage of workers. The
gross pay of a worker depends on the pay rate and the number of hours worked per
week. However, if a worker puts in more than 40 hours in a week, the worker gets
paid time-and-a-half for every hour worked above 40.

Solution:

1. get hours worked


2. get pay rate
3. if hours worked ≤ 40 then
3.1 gross pay = pay rate times hours worked
4. else
4.1 gross pay = pay rate times 40 plus 1.5 times pay rate times (hours
worked minus 40)
5. display gross pay

17
6. end

Variables: hours worked, pay rate, gross pay

Example 2 introduces the decision control structure with the True/False question
asked in line 3. Based on the response, line 3.1 is executed if the answer is True,
otherwise, line 4.1 is executed if the answer is False. Whatever be the case the
pseudocode resumes operation at line 5.

Example 3:

Design a pseudocode for a program which computes student average after a semester
exam.

Solution:

1. get number of courses


2. initialize sum to 0
3. initialize count 0
4. while count < number of courses
4.1 get course score
4.2 sum = sum + course score
4.3 count = count + 1
5. average = sum / number of courses
6. display average
7. end

Variables: number of courses, sum, count, course score, average

In the above Example, the iteration control structure is introduced. As long as the
condition in line 4 is True, the subordinate instructions 4.1 - 4.3 will continue to
execute. When the condition becomes False, the pseudocode resumes at line 5.

FLOWCHART

Flowchart is the graphical representation of an algorithm. It is often used in the design


phase of programming to work out the logical flow of a program. It is believed
that flowchart helps one to visualize an algorithm, and to understand a process,
and perhaps also find flaws, bottlenecks, and other less-obvious features within it.

Dataflow diagram (DFD), and the activity diagram of the universal modeling
language (UML), are essentially the extensions of flowchart. DFDs are used in
structured systems analysis to show the various elements in the system, and the

18
dataflow between these processing elements and the major stores of data within
the system. On the other hand, UML activity diagrams are used in object-oriented
analysis for modelling the detailed logic of a business rule.

Flowchart Symbols

The following is a table showing the flowchart symbols, their name as well as their
uses.

Table 2: Flowchart Symbols

Symbol Name Usage

Oval Denotes the beginning or end of an algorithm

Arrow Denotes the direction of logic flow in an algorithm

Parallelogram Denotes either an input operation or an output


operation

Rectangle Denotes a process to be carried out, e.g. an addition

Diamond Denotes a decision, commonly a Yes/No question or


True/False test

Predefined Denotes a named process or subroutine that may be


Process detailed in separate flowchart

Small Circle Used to make connection between two flowcharts on


the same page

Up Arrow Used to make connection between multi-sheet


diagrams to indicate exit or entry to a page

How to Design Flowcharts

We shall demonstrate how to design flowcharts by repeating the examples under


pseudocode and use flowcharts to implement them. The examples are presented
as follows with the pseudocode solutions also shown once again for comparison.

Example 4:

19
Design a flowchart for a program which computes the final price of a product after
adding the value added tax (vat).

Solution:

Pseudocode

1. get price of product


2. get vat rate
3. vat = price of product times vat rate
4. final price = price of product plus vat
5. display final price
6. end

Flowchart

Start

Input PRICE

Input VAT RATE

VAT
VAT==PRICE
PRICEXXVAT
VATRATE
RATE

FINAL
FINALPRICE
PRICE==PRICE
PRICE++VAT
VAT

Print FINAL PRICE

End

Example 5:

Design a flowchart for a program which computes the weekly wage of workers. The
gross pay of a worker depends on the pay rate and the number of hours worked per
week. However, if a worker puts in more than 40 hours in a week, the worker gets
paid time-and-a-half for every hour worked above 40.

20
Solution:

Pseudocode
1. get hours worked
2. get pay rate
3. if hours worked ≤ 40 then
3.1 gross pay = pay rate times hours worked
4. else
4.1 gross pay = pay rate times 40 plus 1.5 times pay rate
Times (hours worked minus 40)
5. display gross pay
6. end

Flowchart

Start

Input HOURS

Input PAY RATE

HOURES ≤
40
?

GROSS
GROSSPAY
PAY==PAY
PAYRATE
RATEXX4040 GROSS
GROSSPAY
PAY==HOURS
HOURSXXPAY
PAYRATE
RATE
++1.5
1.5XX(HOURS
(HOURS––40)
40)

Print GROSS PAY

End

Example 6:

Design a flowchart for a program which computes student average after a semester
exam.

21
Solution:

1. get number of courses


2. initialize sum to 0
3. initialize count 0
4. while count < number of courses
4.1 get course score
4.2 sum = sum + course score
4.3 count = count + 1
5. average = sum / number of courses
6. display average
7. end

Flowchart

Start

SUM
SUM==00

COUNT
COUNT==00

Input NUMBER OF COURSES

Input SCORE

SUM
SUM==SUM
SUM++SCORE
SCORE

COUNT
COUNT==COUNT
COUNT++11

COUNT <
NUMBER
OF
COURSES

AVERAGE
AVERAGE==SUM/NUMBER
SUM/NUMBEROF
OFCOURSES
COURSES

Print GROSS PAY


22

End
CHAPTER FIVE

INTRODUCTION TO BASIC

As we have pointed out previously, the Beginner's All-purpose Symbolic Instruction


Code (BASIC) is our language of choice in this book for teaching computer
programming. Our choice of BASIC is predicated on its design principles which meet
the objective of an introductory course in computer programming.

According to the Wikipedia online encyclopedia, the eight design principles of


BASIC include:

1. Be easy for beginners to use


2. Be a general-purpose programming language
3. Allow advanced features to be added for experts (while keeping the language
simple for beginners)
4. Be interactive
5. Provide clear and friendly error messages
6. Respond quickly for small programs
7. Not to require an understanding of computer hardware
8. Shield the user from the operating system.

History

The original BASIC language was designed in 1963 by John Kemeny and Thomas
Kurtz and implemented by a team of Dartmouth students under their direction.
BASIC was designed to allow students to write programs for the Dartmouth Time-
Sharing System. It was intended to address the complexity issues of older languages

23
with a new language design specifically for the new class of users that time-sharing
systems allowed—that is, a less technical user who did not have the mathematical
background of the more traditional users and was not interested in acquiring it. Being
able to use a computer to support teaching and research was quite novel at the time. In
the following years, as other dialects of BASIC appeared, Kemeny and Kurtz's
original BASIC dialect became known as Dartmouth BASIC.

BASIC was based partly on FORTRAN II and partly on ALGOL 60, with additions to
make it suitable for timesharing. Initially, BASIC concentrated on supporting
straightforward mathematical work, with matrix arithmetic support from its initial
implementation as a batch language and full string functionality being added by 1965.
At the time of its introduction, it was a compiled language. It was also quite efficient,
beating FORTRAN II and ALGOL 60 implementations on the 265 at several fairly
computationally intensive (at the time) programming problems such as numerical
integration by Simpson's Rule.

The last requirement above will involve the following processes:


Write a program in a particular computer language
Compile the program
Run the program
Debug the program
Repeat the whole process (a-d) until the program is certified ok

How to Run QBasic

This appendix assumes that you have QBasic on your system. See appendix A if you
do not.
QBasic was written to run on old Microsoft operating systems, starting with DOS 5.0
and does not behave like modern software. At first this can be frustrating because
many of the things you would expect to do with the mouse must be done using a
menu.
There are many ways to do the things discussed below. After you have run through
the process a few times, feel free to experiment.
Chapter 1

QUESTION 1:

With a calculator does it matter in which order you push the buttons?

Answer:

24
Yes.

Programs

When you use a calculator to compute 10 plus 5, you must push:

10
+
5
=

... in exactly that order. Pushing

+
10
=
5

... will not work. The order is important. The same is true for computer
programs.

A program is like a recipe for baking cookies: it is a list of instructions which


are followed one-by-one in the correct order.

QUESTION 2:

Isn't it odd that a machine can follow a list of instructions?

Answer:

Yes. Until a few decades ago few people believed that this was possible. One
of the intellectual goals of this course is for you to understand how machines
can follow instructions.

25
Example Program
A QBasic program consists of lines of text, one after another, like a poem.
Each line of a program (or a poem) stays by itself on one line. A line which
has an instruction for the computer is called a statement. Not all lines are
statements. Some lines are blank. Others are comments intended for a
human reader, but not for the computer. Only a line that contains an
instruction for the computer is a statement.

Usually the computer runs a program starting with the first statement and
proceeding statement by statement until the end of the program is reached.

Here is a complete QBasic program as you see it when you are working with
the QBasic system:

Look in Appendix B to see how to enter and run programs. You don't have to
do that now to read this chapter. The picture shows many details that are not
important right now. The QBasic program is just these two lines:

PRINT 10 + 5
END

The PRINT statement causes something to be printed on the screen of the


computer monitor. The last statement in the program is END, which just tells
the computer that the program is finished.

QUESTION 3:

How many statements are in this program?

Answer:

Two.

END is a statement. It tells the system to end this run of the program.

26
Two Statement Programs
Look at the program:

PRINT 10 + 5
END

If you run this program, the computer starts with the first statement:

PRINT 10 + 5

That statement says to:

• Add the number 10 to the number 5


• Print the result on the computer monitor (the computer screen).

This is like an electronic calculator where you enter 10, +, 5, and =. The
calculator then shows 15.

In QBasic there are many things that can be done with the sum. To see the
sum on the monitor, use PRINT.

QUESTION 4:

What do you think the above program prints on the computer monitor?

Answer:

15

The END Statement


The statement PRINT 10 + 5 adds 10 to 5 and then prints the
result 15 on the monitor. Here is what you see on your computer's screen
when you run this program:

27
Don't get lost in the details. The part that the program printed is the number
"15". All the other stuff is unimportant and depends on what computer you are
using.

Here is the program again:

PRINT 10 + 5
END

The last statement, END signals the end of the program. It is obvious where
this program ends, but it is harder to tell with longer programs, so the END
statement is necessary for them.

QUESTION 5:

Do you suppose that the following program is correct?

Answer:

No, the program is not correct. The computer follows instructions in order. If
the first instruction is END the computer ends its run of the program.

Comments
If you run the program again, the computer will start at the first statement
again (and end immediately, as before). Here is another program:

' Program to add two numbers


PRINT 10 + 5
END

The first line of this program is called a comment. A comment starts with an
apostrophe ( ' ). This is the character just left of the Enter key on the
computer's keyboard. Comment lines tell humans what the program does, or
what parts of the program do. When the program is run, the computer does
not look at the comments at all. The comment lines have no effect on what the
program does.

QUESTION 6:

What does the above program do?

Answer:

28
The program adds 10 to 5 and prints 15 on the monitor.

Comments are Ignored by QBasic


The new program does exactly the same thing as the old program. The two
programs are the same except for the comment in the new program. Since
comments are ignored, the two programs do the same thing when they are
run.

Comments are intended to make it easier for humans to figure out what a
program does. When you write a program, you should use comments to
explain what you are doing. QBasic ignores comments and just does what the
statements ask.

QUESTION 7:

Write a program that adds 1.5 to 4.2 and prints the result on the monitor.

(Write the program with paper and pencil. You can just think the answer, if
you want, but please try to answer before continuing.)

Answer:

' Program to add two numbers


PRINT 1.5 + 4.2
END

If you run this program it prints 5.7 on the computer monitor.

Floating Point Numbers


The numbers that you use with QBasic are the same as those you use with an
electronic calculator. You can use numbers that include a decimal fraction
such as the two numbers above.

Numbers such as 1.5 or 3.14159 or 123.821 are called floating point numbers
because the decimal point "floats" among the digits to get to the correct
location. A number without a decimal point, such as 12 or -23 or 194, is called
an integer.

QBasic can do anything an electronic calculator can do (and much more). For
example, it can multiply numbers. To multiply numbers, use * instead of the

29
usual multiply symbol (which is not on the computer keyboard). The character
* is on the same key as "8" on the computer keyboard.

QUESTION 8:

Write a program that MULTIPLIES 12.1 by 2 and prints the result on the
monitor. (Write the program on a scrap of paper.)

Answer:

' Program to multiply two numbers


PRINT 12.1 * 2
END

If you run this program it prints 24.2 on the computer monitor.

Strings
Computers do more than arithmetic. You have probably used a computer for
word processing or for viewing documents on the Web (such as this one).
QBasic may be used with words, too. Here is a program that writes Hello
World onto the monitor screen:

' Program to write words to the monitor


PRINT "Hello World"
END

In this program the PRINT statement has exactly what you want printed inside
quotes (" "). When the program runs, the characters inside the quotes are
printed. The quotes are not printed. The "Hello World" is called a string
because what you want to print is a string of characters inside the quotes.

QUESTION 9:

Write a program that prints

The sky is falling.

to the computer monitor.

Answer:

' Chicken Little's Alarm


PRINT "The sky is falling."
END

30
Of course, the comment in your program might not be the same as mine.

Sequential Execution
Characters inside of quotes are printed literally--upper and lower case are
printed exactly as in the string, and punctuation (such as the period at the end
of the sentence) is printed.

When the computer system performs a command given by a QBasic


statement, we say that the statement is executed. Look at the program in the
question (below). There are two PRINT statements. The first PRINT
statement is executed first (of course), then the second PRINT statement is
executed. Finally the END statement ends the program. Unless directed
otherwise, a QBasic program starts with the first statement and then executes
the statements in sequential order until an END is reached.

QUESTION 10:

What do you suppose this program writes to the computer monitor?

' Program to demonstrate sequential execution


PRINT "Cross patch, draw the latch,"
PRINT "Sit by the fire and spin."
END

Answer:

Cross patch, draw the latch,


Sit by the fire and spin.

The characters (including punctuation) inside the quote marks are printed.
The quote marks are not printed.

Strings and Arithmetic in Print


Statements
A PRINT statement can print more than one item. Examine the following
program.

' Printing two items


PRINT "The sum of 1 plus 10 is", 1 + 10
END

31
The PRINT statement has two items to print:

•A string: "The sum of 1 plus 10 is"


• The result of an adding two numbers: 1+10

The two items are separated by a comma ( , ). When the program runs it
prints the following to the monitor:

The sum of 1 plus 10 is 11

The string is printed unchanged, character for character. The next item is
separated from the first with some spaces, then the result of the arithmetic is
printed. It is useful to list two (or more) items in one PRINT statement.

QUESTION 11:

Here is a program that calculates 12 times 12. The program prints a sting and
then prints the answer. But is the program correct?

' Compute 12 times 12


PRINT "The square of 12" is 12*12
END

Answer:

No. The PRINT statement is wrong. The words inside the quotes must
include the is. The first item to print must be followed by a comma. It is very
easy to overlook such small mistakes.

Here is the correct version of the program:

' Computing 12 times 12


PRINT "The square of 12 is", 12*12
END

Syntax Errors
If you tried to run the incorrect version of the program it would not work. You
would see something on your screen like this:

32
(These notes have not explained how to run programs yet. Just pretend you
tried to run the program). The gray box contains an error message that does
not make much sense. To get rid of the box, hit the TAB key on your keyboard
until the OK in the error message is selected, and then hit ENTER. (Unless
you fix the mistake the error message will appear the next time you run the
program.)

QBasic did not execute the PRINT statement because it has a Syntax Error.
Syntax in programming languages means nearly the same as grammar
means in human languages. It means "the rules for creating a correctly
formed statement."

A statement without syntax errors is formed correctly. It might not make any
sense. This is true with English also. The following is not an English sentence:

be you force may the with

It does not follow English syntax rules and is just a jumble of words. The
following sentence has no syntax errors. But it does not make sense:

The distant corners softly remember grape soda.

QUESTION 12:

Is there a syntax error in the following program?

' Computing 12 times 12


PRINT The square of 12 is, 12*12
END

Answer:

Yes. The string in the PRINT statement does not have quotes around it.

33
Bugs
The program should be:

' Computing 12 times 12


PRINT "The square of 12 is", 12*12
END

If you try to run the incorrect version you get a message window on your
computer screen that lists the problem. (Often the message is hard to
understand. Some syntax errors confuse the QBasic system so badly it does
not know what to do.) Hopefully you can figure out the syntax error, correct it,
and run the program.

Programs can have errors other than syntax errors. Just as you can say
something in grammatical English that is incorrect, you can write a program in
QBasic that has no syntax errors but computes an incorrect result. Such a
program has one or more bugs.

QUESTION 13:

Does the following program make sense?

' Computing 12 times 12


PRINT "The square of 12 is", 12 * 0
END

Answer:

No. The PRINT statement

PRINT "The square of 12 is", 12 * 0

is correct in syntax, but it does not calculate what it should. 12 * 0 means to


multiply 12 by 0, which results in a zero, which is not what is wanted. This
program has a bug.

More Bugs
The buggy program:

' Computing 12 times 12


PRINT "The square of 12 is", 12 * 0
END

34
. . . has a comment line that says what is wanted, and even has a string in the
PRINT statement that said what the result should be. But the arithmetic is
wrong, and a wrong number is printed.

QUESTION 14:

Does the following program have a syntax error or a bug?

' Computing 23.8 plus 5.2


PRINT "The sum is", 23.8 * 5.2
END

Answer:

If the comment is correct, then the program has a bug since in the PRINT
statement the two numbers are multiplied, not added.

A Story Problem
Here is the corrected program:

' Computing 23.8 and 5.2


PRINT "The sum is", 23.8 + 5.2
END

Often the numbers in a computer program are the values of things in real life.
For example, say that one number is "the number of hours you have worked".
The other number is "the number of dollars you are paid per hour". These are
very interesting numbers. The two numbers multiplied together give the
number of dollars you are paid (before deductions).

QUESTION 15:

Write a QBasic program that calculates how much you are paid if you work 16
hours and your rate of pay is 7.25 dollars per hour.

Answer:

' Calculate gross pay


PRINT "The pay is", 16 * 7.25
END

If you run this program it writes:

The pay is 116

35
Arithmetic Operators
So far we have seen the QBasic commands for adding two numbers (+) and
for multiplying two numbers (*). The + and * are called arithmetic operators.
Here is a list of more of them:

Arithmetic Operators

operator meaning example in words

^ power 3^2 3 to the power 2

- negation -23 negative 23

* multiply 1.5 * 8 1.5 times 8

/ divide 12 / 4 12 divided by 4

+ addition 4.2 + 3 4.2 plus 3

- subtraction 9 - 2 9 minus 2

Here is a program that calculates the number of miles per gallon for a car that
has burned 10 gallons of gas and gone 245.4 miles:

' Calculate miles per gallon


' 245.4 miles with 10 gallons of gas
'
PRINT "MPG is", 245.4 / 10
END

It is important to get the two numbers in the correct order. The program is
correct because it divides the number of miles, 245.4, by the number of
gallons, 10. The program prints its output to the monitor:

MPG is 24.54

This program has three comment lines. This is fine; comments are ignored by
the computer. You can have many of them. The third comment line has
nothing on it except for the apostrophe ( ' ) that makes it a comment. This is
fine. You can use a blank line if you want.

QUESTION 16:

Write (on paper, in your head, or on a computer) a program to answer the


following problem:

36
A bird watcher bought 25 pounds of bird food for an outdoor bird feeder. The
birds ate all the food in 15 days. How many pounds of bird food per day did
the birds eat?

Answer:

' Calculate the number of pounds of food


' birds eat in a day if they eat 25 pounds of food
' in 15 days
'
PRINT "Daily seed use is ", 25 / 15, " pounds per day"
END

Your program probably has different strings in the PRINT statement. The
division is correct: 25 pounds divided by the number of days gives pounds per
day. The other arrangement 15/25 is incorrect.

Three items in the PRINT statement


The PRINT statement has three items to print. This is OK, and makes the
program's output more understandable. Each item is separated by a comma.
The three items to print are:

1. A string -- "Daily seed use is "


2. An arithmetic result -- 25 / 15
3. A string -- " pounds per day"

When printed, each item is separated from the previous item by a tab. This is
like pushing the tab key on a typewriter or wordprocessor. The comma ","
separating items is replaced with several spaces (not always the same
number of spaces).

The above program writes the following to the computer monitor screen:

Daily seed use is 1.66666667 pounds per day

QUESTION 17:

The electricity used in a household was 1679 kilowatt hours during 41 winter
days. The same household used 752 kilowatt hours during 31 summer days.
Write a program which uses two PRINT statements to write out the average
kilowatt hours used per day in the winter and the average kilowatt hours used
per day in the summer.

37
Answer:

' Calculate the average KWH per day for winter and summer.
' 1679 KWH used in 41 winter days.
' 752 KWH used in 31 summer days.
'
PRINT "Average WINTER use is ", 1679/41, " KWH per day"
PRINT "Average SUMMER use is ", 752/31, " KWH per day"
END

This program uses sequential execution. The first PRINT statement executes,
then the second PRINT statement executes. Then the END statement stops
the program. The program prints this to the monitor:

Average WINTER use is 40.95122 KWH/day


Average SUMMER use is 24.25806 KWH/day

Negative Numbers
Look at the table of arithmetic operators. The symbol - (minus) appears twice
in the table. This is because it has two meanings:

• The first meaning is "negative number".


• The second meaning is "subtraction".

Arithmetic Operators

operator meaning example in words

^ power 3^2 3 to the power 2

- negation -23 negative 23

* multiply 1.5 * 8 1.5 times 8

/ divide 12 / 4 12 divided by 4

+ addition 4.2 + 3 4.2 plus 3

- subtraction 9 - 2 9 minus 2

These two meanings are the same as in ordinary arithmetic. You may be so
familiar with these two meanings that you may have trouble seeing them. For
example, look at the following, which might be found in a math book (or in any
textbook):

-25 negative 25
-5.2 negative 5.2

18.1 - 2.4 18.1 minus 2.4

38
12 - 6 12 minus 6

The "-" sign is used for two purposes in the above. QBasic uses it for the
same two purposes.

QUESTION 18:

What does the "-" do in the following program?

PRINT "Usual gain in buying a lottery ticket ", -1


END

Answer:

The "-" sign makes a negative number.

Automatic Formatting of Arithmetic


Often, both uses of "-" appear in one calculation. Examine the following:

-25 + 10 negative 25 plus 10 = -15


-5.2 - 3.1 negative 5.2 minus 3.1 = -8.3
18.4 - 2.4 18.4 minus 2.4 = 16.0
-12/6 minus 12 divided by 6 = -2

The QBasic system makes this less confusing by adjusting what you type.
QBasic adjusts what you type so that:

• When "-" means "negative number" it is placed right up against


the number it is for.
• When "-" means "subtraction" it is separated from the numbers
to be subtracted by one space on each side.

For example, if you type:

PRINT - 25
END

QBasic adjusts this to:

PRINT -25
END

(The adjustment is not done until after the cursor has left the line.)

QUESTION 19:
39
You type the following:

PRINT - 25-4

How will QBasic adjust this line?

Answer:

PRINT -25 - 4

The first minus sign means "negative number" and is moved right up against
the 25. The second minus sign means "subtract" and is separated by spaces
on either side.

More about Negative Numbers


The above statement subtracts 4 from a negative 25. This results in -29.

QUESTION 20:

What will the following program print on the monitor?

PRINT -16 + 4
END

Answer:

The statement PRINT -16 + 4 causes -12 to be printed on the


monitor. The arithmetic -16 + 4 means "add four to negative sixteen."
The - sign indicates a negative number.

Exponents
The exponentiation operator is ^ (on the same key as 6). It means "to the
power of".

3^2 means three to the power two, = 3 * 3 = 9

4^3 means four to the power three, = 4 * 4 * 4 = 64

2.5^2 means 2.5 to the power two, = 2.5 * 2.5 = 6.25

10^1.2 means ten to the power 1.2, = 15.8489

40
You may not have seen fractional powers before as in the last example. Don't
worry. We won't use them. But if your need it in the future, QBasic can do it.

QUESTION 21:

What (do you suppose) that the following program writes?

' Number of square inches in a square foot


PRINT "Square inches = ", 12 ^ 2
END

Answer:

Square inches = 144

Several Operators in a Row


Sometimes you want more than one arithmetic operator in the same
statement. For example, here is a program to calculate the number of fluid
ounces in a gallon:

' Number of fluid oz. in a gal.


'
' There are 16 oz. per pint
' There are 2 pints per quart
' There are 4 quarts per gal.
'
PRINT "Fluid ounces = ", 16 * 2 * 4
END

When you see two or more of the same operator, start at the left and do them
one at a time:

16 * 2 * 4 32 * 4 128
------
do first

Often it makes no difference in what order you do the arithmetic when all
operators are the same. In more complicated floating point arithmetic it
sometimes makes a difference.

QUESTION 22:

Write a program that calculates the number of Winter days in a year.

• There are 11 Winter days in December

41
• There are 31 Winter days in January
• There are 28 Winter days in February (usually)
• There are 19 Winter days in March
• Answer:
• ' Number of Winter Days
• '
• PRINT "Winter Days = ", 11 + 31 + 28 + 19
• END
• When all the operators are the same, start at the left and do the
arithmetic one operator at a time. Doing this for the above:
• 11 + 31 + 28 + 19 42 + 28 + 19 70 + 19 89
• -------- -------- -------
• do first do second do third

• End of the Chapter


Chapter 2

Answer:

Yes, (8 + 12) / 2 looks right. You don't need to memorize rules to


decide this.

Arithmetic Expressions
An arithmetic expression is a syntactically correct combination of numbers,
operators, parenthesis, and variables.

You have not (officially) seen variables yet, so ignore that part of the
definition. Here are several arithmetic expressions, similar to those you saw in
the previous chapter:

25 + 15 32.128 - 19.6 + 3.2

-14 / 3 1.243 ^ 5

-23.77 * -2 10 - 5 - 8

Remember that syntax means the rules for putting together a correctly
formed statement. Arithmetic expressions are parts of statements, so must
follow syntax rules in order to be correct. You are already familiar with these
rules: they are the same rules as for pencil-and-paper arithmetic.

QUESTION 2:

42
Is the following an arithmetic expression?

89.3 + / 2

Answer:

No, 89.3 + / 2 is not syntactically correct, so cannot be an


arithmetic expression.

Notice that 89.3 + / 2 is made of correct components—numbers and


operators—but that they are put together incorrectly.

Which Operator is done First?


When two or more arithmetic operators are used in the same arithmetic
expression it is sometimes not clear what to do. For example:

1 + 2 * 3 = ?

This could mean either of two things, depending on what operation is done
first:

1 + 2 * 3 = 3 * 3 = 9
-----

OR

1 + 2 * 3 = 1 + 6 = 7
-----

It is not clear if + or if * should be done first. Which one is done first makes a
difference in the result.

QUESTION 3:

What is the usual (paper-and-pencil) meaning of

1 + 2 * 3

43
What do you think is the usual meaning of

1 + 2 * 3 ?

Answer:

Usually 1 + 2 * 3 means to do the multiplication first.

Operator Priority
To clear up these problems, arithmetic operators have each been given a
priority. When there is a choice, do the highest priority operation first. The
priorities of operators is given in the table. The highest priority is "1" and the
lowest is "4".

Priority of Arithmetic Operators

operator meaning priority

^ power 1

- negation 2

* multiply 3

/ divide 3

+ addition 4

- subtraction 4

For example:

1 + 2 * 3
-------
* has higher priority than +, so do first

= 1 + 6

= 7

QUESTION 4:

Do this:

2 * 3 + 1

44
Answer:

2 * 3 + 1 = 6 + 1 = 7
--+--
|
higher priority
than +,
do first

More on Operator Priority


When there are two or more operators of different priority, do the highest
priority operator first. If there are several operators of the same priority do the
operators from left to right. (Except for exponentiation, ^, which is done right
to left.) Examine the following:

4 + 3 * 4 + 2

4 + 3 * 4 + 2 --- pick the highest priority operator


-----

4 + 12 + 2 --- all operators are of same priority


------ so do them left to right

16 + 2

18

Since * has the highest priority it is done first.

After doing * there are two + operators left. These are done left to right
(although in this case it does not make a difference.)

QUESTION 5:

What is the result of the following?

10 + 3 * 3 + 5

Answer:

The highest priority operator in

10 + 3 * 3 + 5

is *, so it is done first. This gives

45
10 + 9 + 5.

Now the remaining + are of equal priority and are done left to right.

10 + 9 + 5 = 19 + Priority of Arithmetic Operators


5 = 24
operator meaning priority

Equal Priority ^

-
power

negation
1

2
for * and / * multiply 3

/ divide 3
Examine the priority chart again:
Notice that * and / have the same + addition 4
priority. When there are several * - subtraction 4
and /, do them left to right. For
example:

12 / 3 * 2 --- all operators have same priority


------ do them left to right

4 * 2

The / and * have equal priority. The operators are done left to right.

QUESTION 6:

What is the result of the following?

10 * 2 / 4

Answer:

There are two operators of equal priority in

10 * 2 / 4

so they are done in order left to right:

10 * 2 / 4 = 20 / 4 = 5
------
.

46
+ and - have Equal Priority
Notice that + and - also have equal priority. If they are the only operators in an
expression, do the work from left to right.

QUESTION 7:

What is the result of the following?

12 - 2 + 4

Answer:

There are two operators of equal priority in

12 - 2 + 4

so they are done in order left to right:

12 - 2 + 4 = 10 + 4 = 14
------
.

Mixtures of * / and + -
When the operators in an arithmetic expression have a mixture of priorities,
remember to do the highest priority first. If there are many operators in an
expression, first find the highest priority operators. The leftmost of them will be
done first. (However power, ^, is an exception to this rule. But for clarity you
should never use two ^ in a row, although this is legal.)

QUESTION 8:

In the following, what operator is done first?

2 * 4 + 3 - 8 / 4

Answer:

2 * 4 + 3 - 8 / 2 = 2 * 4 + 3 - 8 / 2
-----

47
* and / have the same priority, so do the leftmost of them first. The + and the -
share a lower priority so they will not be done until later.

Same Example
After the first operation ( * ) is done, the result is:

2 * 4 + 3 - 8 / 2 = 8 + 3 - 8 / 2
-----

QUESTION 9:

What operator is done next?

8 + 3 - 8 / 2

Answer:

8 + 3 - 8 / 2 = 8 + 3 - 4
-----

The single / has higher priority than the + and the -, so it is done first. Now
there are two operators of equal priority, so they are done left to right:

8 + 3 - 4 = 11 + 4 = 15
-----
Priority of Arithmetic Operators

Negative operator meaning priority

^ power 1
Numbers (again) - negation 2

* multiply 3
Examine the operator priority chart
again. Notice that "-" is in the chart / divide 3
in two places. As you saw in
+ addition 4
chapter one, this is because "-" is
used in two different ways: - subtraction 4

• The first meaning is "negative number". This use has high


priority.
• The second meaning is "subtraction". This use has low priority.

Since "negation" has high priority, it will be done first:

10 + -8 / 2 = 10 + (-8)/2 = 10 + -4 = 6

48
QUESTION 10:

What is the result of the following?

-12 + 2 + 4

Answer:

In the expression -12 + 2 + 4 the "-" means "negative" and is firmly


attached to the 12:

-12 + 2 + 4 = (-12) + 2 + 4 = (-10) + 4 = -6


--- --------- ---------

Once the negative is attached to the 12, the rest is done by going left to right
since the two + are of equal priority.
Priority of Arithmetic Operators

Exponents operator meaning priority

^ power 1
In the priority chart, exponent is the - negation 2
highest priority of all. This means
* multiply 3
that it will be done before anything
else. Remember that "^" means / divide 3
"raised to the power of".
+ addition 4

QUESTION 11: - subtraction 4

What operator will be done first in the following?

10 * 3 ^ 2 - 5

Answer:

The ^ operator is higher priority than any of the others, so it is done first. (If
you are having trouble remembering priorities, notice that the operators from
lowest to highest priority are the same order you learned them in grade
school.)

10 * 3 ^ 2 - 5 = 10 * 9 - 5
-----

49
Now the rest follows the usual order: 10 * 9 - 5 = 90 - 5 = 85.

Arithmetic in Basic Programs


We are still talking about QBasic programs. Arithmetic expressions are just a
part of them. Now that you know about operator priority you should be able to
do more complicated arithmetic in PRINT statements (and elsewhere, when
we get to it...)

QUESTION 12:

What will the following program print to the monitor?

' Mixed Operators


'
PRINT 3 + 12 / 2
END

Answer:

The program will print 9 to the monitor, because:

3 + 12 / 2 = 3 + 6 = 9

A Story Problem
Remembering operator priority makes it easier to get the arithmetic right in
story problems. Recall the fluid ounces measure of volume:

• 16 fl. oz. per pint


• 32 fl. oz. per quart
• 12 fl. oz. per most beverage cans

QUESTION 13:

While studying for a final exam, you stayed up all night. The next day you find
the following empty containers in your room:

• Three 12 oz. cans of Jolt


• Two pint bottles of Mountain Dew
• One quart bottle of Pepsi

50
Write a program to print out how many fluid ounces of beverage you
consumed.

Answer:

' Fluid oz. of beverage


'
PRINT 3 * 12 + 2 * 16 + 32, " ounces consumed"
END

• Three 12 oz. cans of Jolt = 3 * 12 ounces


• Two pint bottles of Mountain Dew = 2 * 16 ounces
• One quart bottle of Pepsi = 32 ounces

The program prints:

100 ounces consumed

Because of operator priority, the number of each type of container was


multiplied by the container size.

(Parentheses)
Just as in ordinary algebra, parentheses may be used in arithmetic
expressions to re-arrange the order in which operations are performed.
Arithmetic inside parentheses is done first. So

(10 + 6) / 2

means "add 10 to 6" then divide the result by 2. Here is a program to average
two numbers:

'Compute the average of 10 and 6


'
PRINT "The average is", (10 + 6) / 2
END

Without using ( ) this program would be hard to write.

QUESTION 14:

You have taken three tests in a course and received the grades:

• 68 (the Jolt all-nighter did not help)


• 84
• 92

51
Write a program to print out the average of your test grades.

Answer:

' Average of three test grades


'
PRINT "Average Test Grade:", (68 + 84 + 92) / 3
END

When the PRINT statement executes will do the arithmetic (first the addition,
then the division).

(68 + 84 + 92) / 3 = 244 / 3 = 81.33333


--------------
do first

Then it will print to the monitor:

Average Test Grade: 81.33333

(Parentheses) and Division


A common combination is to divide the sum of several numbers by the sum of
several other numbers. In paper-and-pencil arithmetic this might look like:

12 - 8 + 4
----------
2 + 6

The big horizontal division line makes the grouping clear: the arithmetic above
the line is done, then the arithmetic below the line is done, and then the two
results are divided. In QBasic do this with TWO SETS of parentheses:

(12 - 8 + 4) / (2 + 6)

The insides of BOTH sets of ( ) must be done before the division is


performed. So the above is done like:

(12 - 8 + 4) / (2 + 6) = 8 / (2 + 6) = 8 / 8 = 1
------------ -------
first next

QUESTION 15:

What will the following program write to the monitor:

' Division example

52
'
PRINT (10 + 2) / (3 + 3)
END

Answer:

(10 + 2) / (3 + 3) = 12 / (3 + 3) = 12 / 6 = 2
-------- -------
do first do next

Miles per Gallon


Problems asking for "miles per gallon" or "dollars per hour" or "pounds per
calorie" are asking for the first value (say miles) to be divided by the second
value (say gallon). Sometimes the two values are not given directly--so you
must do subtraction or addition before doing the division for the "per".

QUESTION 16:

When the gas tank of an automobile was first filled the odometer read
53,438.5 miles. When the tank was next filled the odometer read 53,659.2
miles and needed 8.23 gallons of gasoline.

Examine the following program. Will it correctly calculate miles per gallon?

' Miles per Gallon


'
PRINT "miles per gallon =", 53659.2 - 53438.5 / 8.23
END

Answer:

No — parenthesis are needed around the two odometer readings so that the
number of miles are calculated first, and the division is carried out second:

' Corrected Miles per Gallon


'
PRINT "miles per gallon =", (53659.2 - 53438.5) / 8.23
END

No Commas inside of Numbers

53
When large numbers are written on paper, commas are used to make them
more readable. In QBasic, numbers do not have commas inside of them

QUESTION 17:

For your graduation party you buy a 5 gallon keg of grape soda. After the
party, the keg has 1.5 gallons still left in it. How many 8 ounce glasses of
grape soda did your guests drink? (There are 128 fluid ounces per gallon.)

Write a program to solve this problem.

Answer:

' Glasses of Grape soda


'
PRINT "glasses of soda =", 128 * (5 - 1.5) / 8
END

The parentheses are needed:

• Number of gallons used = (5 - 1.5)


• Number of ounces in the gallons used = 128 * (5 - 1.5)
• Number of 8 ounce glasses of soda = 128 * (5 - 1.5) / 8

(Extra Parenthesis)
In the above program we relied on both parentheses and operator priority to
do the arithmetic in the correct order:

128 * ( 5 - 1.5 ) / 8 = 128 * 3.5 / 8 = 448 / 8 = 56


----------- ---------- -------
do first do next do last

Remember that since * and / have equal priority, when there are two of them
in an expression the leftmost is done first.

Sometimes you would like to use parentheses to carefully show in what order
the arithmetic will be done, even if the parentheses are not really needed. For
example, the above program could have been written as:

' Glasses of Grape soda


'
PRINT "glasses of soda =", (128 * (5 - 1.5)) / 8
END
^ ^

54
The two parentheses marked with a "^" are not needed. This program will
calculate and print exactly the same thing as the previous program. But now
the extra parentheses make clear what will be done before the division by 8 is
carried out.

QUESTION 18:

What will the following program print?

' Extra Parentheses


'
PRINT (12 - 6 + 2)
END

Answer:

The rule for parentheses is that what is inside parentheses is calculated first.
In (12 - 6 + 2) everything is inside parentheses, so the
parentheses don't have any effect. But they don't hurt anything.

Nested Parenthesis
When there are sets of parentheses inside parentheses the innermost set of
parentheses is calculated first. The innermost set of parentheses are nested
within the outer set. For example:

( 5 * (1 + 2) ) / 3 = ( 5 * 3 ) / 3 = 15 / 3 = 5
------- ---------
innermost do next
so do first

QUESTION 19:

What will the following program print to the screen:

PRINT (4 * (10 - 7)) / 6

Answer:

2 is printed to the monitor:

(4 * (10 - 7) ) / 6 = (4 * 3) / 6 = 12 / 6 = 2

55
------ -------
first second

Complicated Pricing
Examine the following story problem:

Bob's Copy Shoppe charges 3 cents per page plus 5 cents per staple. You
have a booklet that is made by stapling 7 pages together. Say that you want
25 copies of the booklet.

QUESTION 20:

Will the following program correctly calculate the price?

' Duplicating costs: 7 pages, 3 cents per page, 5 cents per


staple
' 25 copies
PRINT (7 * 3 + 5) * 25 / 100, "dollars"
END

Answer:

Yes -- the program will calculate the correct price in dollars. Study how the
arithmetic is carried out. The value inside the parentheses is the cost in cents
of each booklet. That value is multiplied by the number of copies, 25, to get
the total cost in cents. The total cost in cents is divided by 100 to get the cost
in dollars.

(7 * 3 + 5) * 25 / 100 = (21 + 5) * 25 / 100 = 26 *


25 / 100 =
----------- --------
-------
do first keep working do
next

650 / 100 = 6.50


---------
finally

Arithmetic Inside Parentheses


The first thing done is to work with the parentheses:

(7 * 3 + 5) * 25 / 100 = (21 + 5) * 25 / 100

56
----------- --------
do first keep working

Inside the parentheses are two operators: * and +. Do the * first, because it
has highest priority. Then keep working by doing the +:

(21 + 5) * 25 / 100 = 26 * 25 / 100


--------
keep working

When the insides of the ( ) is completed you are left with a number, 26. The
rest of the work is done using the left to right rule:

26 * 25 / 100 = 650 / 100 = 6.5


-------
leftmost
of two operators of
equal priority

QUESTION 21:

What does the following program print to the monitor?

' Parentheses first


'
PRINT ( 2 * 3 + 2 ) / 4

Answer:

2 is printed to the monitor:

( 2 * 3 + 2 ) / 4 = ( 6 + 2 ) / 4 = 8 / 4 = 2
----- -----

The () is evaluated first, which takes two steps because there are two
operators.

Parenthesis must Match


For every left parenthesis "(" there must be a right parenthesis ")" and the two
( ) must enclose something that makes sense. The following is correct:

( 3 * 3 + 4 ) / 2.3

The following is not correct (it has a SYNTAX error):

( 3 * 3 + ) 4 / 2.3

57
QUESTION 22:

Does the following program have a syntax error?

' Possible error


'
PRINT "Answer is", (5 + 4) / 9 )
END

Answer:

Yes — the program has a syntax error because there is no match for the
rightmost parenthesis. It is not needed. The following program is correct:

' No syntax error


'
PRINT "Answer is", (5 + 4) / 9
END

End of the Chapter


Chapter 3

Variables
In this chapter you will learn about variables in QBasic. Variables enable your
program to remember values from one program statement to the next.

Chapter Topics

• Variables.
• Types of Variables.
• Using Variables in Statements.
• Arithmetic with Variables.
• Changing the contents of Variables.

QUESTION 1:

In algebra, what do you call symbols like "x" and "y" , as in 3x2 + 2y ?

Answer:

variables

58
Variable
Modern computers have a large amount of main memory (also called RAM).
This memory is used for many things. When you run a QBasic program, the
statements of the program are stored in main memory. The data for the
program also can be stored in main memory.

A variable in QBasic is a small amount of computer memory that has been


given a name. You (the programmer) think of the name you want to use. The
QBasic system will use a section of main memory for that name.

A variable is like a small box that holds a value. The value in the variable can
change (that is why it is called a variable). Here is a program that uses a
variable:

' Program that uses a variable


'
LET NUM = 23.5
PRINT "The variable contains", NUM
END

When this program runs, the value 23.5 is placed in the variable NUM. Then
the following is written to the monitor:

The variable contains 23.5

QUESTION 2:

What do you think the following program will write to the monitor?

' Program with a variable


'
LET NUM = 53
PRINT "The variable contains", NUM
END

Answer:

The program prints:

The variable contains 53

The LET Statement


Look at the (first) program again:

59
' Program that uses a variable
'
LET NUM = 23.5
PRINT "The variable contains", NUM
END

In this program, NUM is a variable. The programmer chose the name NUM .
When the program runs, several things happen when the LET statement
executes:

• Memory is reserved for the variable NUM


• The number 23.5 is stored in the variable

So after this statement has executed a section of memory named NUM holds
23.5:

NUM

23.5

After the first statement has executed, the second statement executes:

PRINT "The variable contains", NUM

The variable NUM already exists, so no more memory is reserved for it. The
PRINT statement does several things:

• It prints "The variable contains"


• It looks in the variable NUM for a number.
• It prints out the number it found.

So on the monitor you see:

The variable contains 23.5

QUESTION 3:

What do you think the following program will write to the monitor?

' Program with a variable


'
LET VALUE = 2 + 3
PRINT "The result is", VALUE
END

60
Answer:

The program will print:

The result is 5

Saving a Result
Look at the new program again:

' Program with a variable


'
LET VALUE = 2 + 3
PRINT "The result is", VALUE
END

The first statement does several things:

1. Memory is reserved for the variable VALUE


2. A number is calculated: 2 + 3 = 5
3. The number 5 is stored in the variable.

The LET statement can be used with a variable to save the result of
arithmetic. The value saved in the variable will stay there until another
statement changes it, or until the program stops running.

QUESTION 4:

What do you think the following program will write to the monitor?

' Saving a result in a variable


'
LET SUM = 1 + 2 + 3
PRINT "The sum is", SUM
END

Answer:

The program will print:

The sum is 6

61
Arithmetic with Variables
Look at the following program. Remember the idea of sequential execution:
Unless directed otherwise, a QBasic program runs by starting with the first
statement and executing the statements in sequence.

' Arithmetic with Variables


'
LET AGE = 23
PRINT "You have lived more than", AGE * 365, " days"
END

The first statement, LET AGE = 23 does two things:

• Memory is reserved for the variable AGE


• The value 23 is stored in the variable

So after this statement has executed a section of memory named AGE holds
23:

AGE

23

The first time a particular variable is used in a program, a section of main


memory will be reserved for it.

QUESTION 5:

Can the value in AGE be used in a calculation?

Answer:

Yes. That is the purpose of using variables.

Calculation
After the first statement executes, the second statement executes.

62
PRINT "You have lived more than", AGE*365,
" days"

This statement does several things:

1. It prints "You have lived more than"


2. It looks in the variable AGE for a value to use.
3. It multiplies that value by 365 but DOES NOT change the
contents of AGE .
4. It prints out the result of the calculation.

So on the monitor you see:

You have lived more than 8395 days

QUESTION 6:

What do you think the following program will write to the monitor?

' Pounds to ounces


'
LET POUNDS = 3
PRINT "The number of ounces is ", POUNDS * 16
PRINT "The number of pounds is ", POUNDS
END

Answer:

The program will print:

The number of ounces is 48


The number of pounds is 3

Notice that using the variable POUNDS in the PRINT statement did not
change its contents. The variable POUNDS is like a box that holds a value
you can use as many times as you want without changing it.

Using the Contents of a Variable


The value stored in a variable can be used as many times as you want. Here
is another program that uses a variable many times without changing the
contents.

63
' 5280 feet per Mile
' 1 yard per 3 feet
' 12 inches per foot
'
LET MILE = 5
PRINT "Number of Miles", MILE
PRINT "Number of Yards", MILE * 5280 / 3
PRINT "Number of Feet", MILE * 5280
PRINT "Number of Inches", MILE * 5280 * 12
PRINT "Number of Miles", MILE
END

The first statement finds memory for the variable MILE and puts the value 5
into it:

MILE

The 5 will stay in MILE until you change it (with a second LET statement,
for instance). Using the variable in an arithmetic expression does not change
it. The following statements will execute one after the other, in order. The
program will print out:

Number of Miles 5
Number of Yards 8800
Number of Feet 26400
Number of Inches 316800
Number of Miles 5

Notice that the value 5 in MILE does not change, so the first PRINT
statement and the last PRINT statement write the same thing to the
monitor.

QUESTION 7:

What do you think the following program will write to the monitor?

' Hours of Boring Lectures


'
LET CLASSES = 4
PRINT "Hours per Week", CLASSES * 3
PRINT "Hours per Semester", CLASSES * 3 * 15
PRINT "Ho Hum..."
END

64
Answer:

The program will print:


Hours per Week 12
Hours per Semester 180
Ho Hum...

Names for Variables


Remember that a variable is a small amount of computer memory that has
been given a name. So far you have seen several names for variables:

NUM POUNDS
VALUE MILE
SUM CLASSES
AGE

Names for variables are single words that the programmer picks. The names
don't have to be real words, but it helps in understanding the program if they
are. Look over the following rules. (Just read through them once or twice; you
don't have to memorize them.)

Rules for Variable Names

1. A variable is a small amount of computer memory that has been


given a name.
2. The name is:
o up to 40 characters long,
o the first character must be A-Z, a-z,
o the rest of the characters must be A-Z, a-z, 0-9, or "."
o no spaces are allowed inside of a name.
3. You can't use a word that is already used for something else.
(You can't use PRINT as a name vor a variable.)
4. The last character of the name tells what type of data the
memory holds:
o SUM% holds an integer (no decimal point)
o SUM& holds a potentially very big integer
o SUM holds a floating point number (can have a decimal
point)
o SUM# holds a potentially very big floating point number
o SUM$ holds a string of characters
5. Different names mean different places in memory.
6. The last character is part of the name, (so SUM% and SUM are
different variables.)

65
7. If two names differ only in upper and lower case characters, they
are really the same name.

So far we have been using variables that hold floating point numbers (those
with a possible decimal point like the numbers on a hand calculator.) This type
of variable is the most useful. These variables can hold numbers like 1.3,
-45.78, 0.001, and can also hold numbers without a fractional part like 1.0,
-23.0, 94.0 and others.

QUESTION 8:

Which of the following are OK names to use for a variable that will hold a
floating point number?
SUM GRAND TOTAL
MyValue 16Candles
SUM23 YEAR%

Answer:

SUM --- OK (made up of correct characters, not


too long)
MyValue --- OK (upper and lower case letters can be
used)
SUM23 --- OK (digits can be used after the first
letter)
GRAND TOTAL --- BAD (no spaces allowed)
16Candles --- BAD (digits can't be used as first
character)
YEAR% --- BAD (last character % means this is an
integer variable)

Case Differences in Names


Look at the last rule again:

If two names differ only in upper and lower case characters, they are really
the same name.

This means that:

VALUE Value value vALuE

are really all the same name. In fact, if you try to use more than one of these
versions in your program, the QBasic system will change what you have typed
so that only one version is used. Say that you have typed in the following
program:

66
' Attempt to use two versions of the same name
'
LET VALUE = 123
PRINT value

As soon as you move the cursor out of the PRINT statement the QBasic
system will change your program:

' Attempt to use two versions of the same name


'
LET value = 123
PRINT value

QUESTION 9:

VALUE is the name of a variable. Which of the following name a different


variable?

VALUES value
VALU vALUe
VALUE$ Value

Answer:

VALUES --- different, because it ends with an S


VALU --- different, because the final E is mission
VALUE$ --- different, because the final $ means a
character variable
value --- same
vALUe --- same
Value --- same

One Variable or Two?


A common problem in writing a program is to accidentally use two slightly
different variables names when you want just one variable. The following
program has a BUG:

' Calculate Miles per Gallon (Buggy Version)


'
' second odometer reading is 45,678.3
' first odometer reading is 45,149.6
' gallons of gas used is 12.5
'
LET MILES = (45678.3 - 45149.6)
PRINT MILE / 12.5
END

67
QUESTION 10:

Find the bug in the program, and write a new program that corrects the bug.

Answer:

A correct version of the program is:

' Calculate Miles per Gallon (Correct Version)


'
' second odometer reading is 45,678.3
' first odometer reading is 45,149.6
' gallons of gas used is 12.5
'
LET MILES = (45678.3 - 45149.6)
PRINT MILES / 12.5
END

The buggy program uses two names: MILES and MILE where there
should only be one. Either name is a correct variable name, but you have to
use just one name for the one variable.

When Memory is Found for


Variables
The first time a variable is used in a program, the QBasic system finds
memory for it. This is true for any statement, not just the LET statement. If
there is no other information, the system will put a zero into a number
variable. Here is a buggy program of the previous question:

' Calculate Miles per Gallon (Buggy Version)


'
LET MILES = (45678.3 - 45149.6)
PRINT MILE / 12.5
END

The name MILE in the PRINT statement is the first time that variable
name is seen. (MILES is a completely different name as far as QBasic is
concerned.) So the system finds memory for the new variable MILE, and,
lacking any other information, puts a zero into it. Now there are two variables
in memory:

68
MILES MILE

528.7 0

The arithmetic expression MILE / 12.5 will get the 0 from MILE and
divide it by 12.5, resulting in 0. Finally the PRINT will write to the monitor:

This is a bug, and hard to track down unless you carefully look at the spelling
of each variable name in the program. If a program you write mysteriously
calculates an incorrect answer of zero, check the spelling of each variable!

QUESTION 11:

What do you think the following program will write to the monitor?

' Calculate Miles per Gallon (Buggy? or not?)


'
LET MILE = (45678.3 - 45149.6)
PRINT MILE# / 12.5
END

Answer:

The program will print:

This is because MILE and MILE# are two different names, for two different
variables. MILE# was first used in the PRINT statement, so that is when
memory was found for it. It was initialized to zero, so it held a zero when the
division MILE# / 12.5 was done.

Several Variables in a Program


A program may use many variables. Variables are useful for storing the
intermediate parts of a calculation. Here is a different solution to the program
you saw in chapter two:

Problem: Calculate the number of 8 ounce glasses of grape soda consumed


if a 5 gallon keg of grape soda has 1.5 gallons still left in it. (There are 128
fluid ounces per gallon.)

69
' Glasses of Grape soda
'
LET KEGSIZE = 5 ' statement 1
LET LEFTOVER = 1.5 ' statement 2
LET GALLONS = KEGSIZE - LEFTOVER ' statement 3
LET OUNCES = GALLONS * 128 ' statement 4
PRINT "glasses of soda =", OUNCES / 8 ' statement 5
END

Remember the idea of sequential execution. The statements of this program


will execute one by one in order starting with the first statement.

In statement 1, the variable KEGSIZE is used for the first time, so memory
is found for it. The LET puts a 5 in that memory. Here is what computer main
memory looks like after statement 1 has executed.

KEGSIZE

Now statement 2 executes. Memory is found for the variable LEFTOVER


and the value 1.5 is saved in it:

KEGSIZE LEFTOVER

5 1.5

Statement 3 is more complicated.

LET GALLONS = KEGSIZE - LEFTOVER ' statement 3

This statement does several things:

1. Finds memory for the variable GALLONS


2. Looks in KEGSIZE to get the value 5
3. Looks in LEFTOVER to get the value 1.5
4. Calculates 5 - 1.5
5. Puts the result 3.5 in GALLONS

Remember that using the variables KEGSIZE and LEFTOVER in statement 3


does not change them. After statement 3 has executed, main memory looks
like:

70
KEGSIZE LEFTOVER GALLONS

5 1.5 3.5

When statement 3 is finished, statement 4 executes.

QUESTION 12:

What 4 things does statement 4 do?

LET OUNCES = GALLONS * 128 ' statement 4

Answer:

LET OUNCES = GALLONS * 128 ' statement 4

Statement 4 does 4 things:

1. Finds memory for the variable OUNCES.


2. Looks in GALLONS to get the value 3.5
3. Calculates 3.5 * 128
4. Puts the result 448 in OUNCES.

Step one is performed because OUNCES has not been seen before in this
program so memory must be found for it now.

Last Statement
After statement 4 memory looks like:

KEGSI LEFTOV GALLO OUNC


ZE ER NS ES

5 1.5 3.5 448

(Of course, there are many other things in memory, but we are not concerned
with them now.)

Finally, the last statement is executed:

PRINT "glasses of soda =", OUNCES / 8 ' statement 5

71
QUESTION 13:

What will this statement write to the monitor?

Answer:

The program will print:

glasses of soda = 56

Breaking a Calculation in Two


This statement does four things:

PRINT "glasses of soda =", OUNCES / 8

1. Writes glasses of soda to the monitor.


2. Gets the value 448 from the variable OUNCES.
3. Divides that value by 8 (but leaves the contents of
OUNCES unchanged).
4. Writes the result, 56, to the monitor.

Often part of a calculation is put in a variable and later on used in the rest of
the calculation. This divides the work between several program statements.

QUESTION 14:

Your Grape Soda Keg Party was a success!! However, you discover that your
living room carpet is now purple. A can of carpet cleaner will clean 80 square
feet. Your living room carpet is 12 feet by 17 feet. How many cans or carpet
cleaner do you need?

Write a program to solve this problem using a variable named


SQUAREFEET which will hold the number of square feet in your carpet.

Answer:

' How many cans of cleaner are required for a 12 by 17 ft


carpet?
' One can will clean 80 square feet
'
LET SQUAREFEET = 12 * 17
PRINT "Required cans = ", SQUAREFEET / 80

72
END

The number of square feet in a rectangle is the product of the width and
breadth, here 12 * 17. Divide the number of square feet in the carpet by the
number of square feet one can of cleaner will clean to find the number of cans
needed.

Variables in PRINT statements


The program will write out:

Required cans = 2.55

Often a program calculates several things as it runs and keeps each result in
a variable. Only at the end does the program print out everything it has
calculated by using the variables in a PRINT statement.

QUESTION 15:

Modify the previous program so that it calculates the number of cans of carpet
cleaner and stores the result in a variable called CANS. Use the PRINT
statement to print out SQUAREFEET and CANS and appropriate
captions.

Answer:

' How many cans of cleaner are required for a 12 by 17 ft


carpet?
' One can will clean 80 square feet
'
LET SQUAREFEET = 12 * 17
LET CANS = SQUAREFEET / 80
PRINT "Size of carpet = ", SQUAREFEET, "Required cans = ",
CANS
END

Temporary Variables
Sometimes variables are used inside a program to build up to the answer.
They are used somewhat like "scratch paper" to hold a step along the way to
the result you want. The final PRINT statement might not use them.

73
Consider the following problem: On Valentine's Day you receive a box of 200
chocolates. The packaging makes the following claims:

• 35 percent of the chocolates are filled with caramel.


• 25 percent of the chocolates are filled with coconut.
• 20 percent of the chocolates are filled with cherry cream.
• 10 percent of the chocolates are filled with nuts.
• the remaining 10 percent are solid chocolate.

You dislike coconut and cherry cream chocolates, and won't eat them.

QUESTION 16:

Will the following program correctly calculate how many chocolates you eat
and how many you discard? (Remember that both upper and lower case
letters can be used in names for variables, so all the names are correct.)

' Valentine's Day Treat


'
LET TotalChocolates = 200
LET DiscardPercent = 25 + 20
LET Discard = TotalChocolates * (DiscardPercent / 100)
LET Eaten = TotalChocolates - Discard
PRINT "You will eat", Eaten, "chocolates and throw away",
Discard, "chocolates."
END

Answer:

Yes -- the program is correct.

Story Problem
Remember "percentage" means "parts per 100," so to calculate "how many"
given a percentage you have to divide by 100:

LET Discard = TotalChocolates * (DiscardPercent / 100)

• DiscardPercent is 45.
• DiscardPercent / 100 is 0.45 – the fraction to discard.
• TotalChocolates * (DiscardPercent / 100) is 200 * 0.45 = 90

The program writes:

You will eat 110 chocolates and throw away 90


chocolates.

74
QUESTION 17:

Write a QBasic program that solves the following problem: You have rented
an automobile at $26.59 a day plus 31 cents per mile. After three days you
return the car with 253 miles driven. How much does the car rental cost?

Use two variables DAYS and MILES to hold values.

Answer:

' Cost of renting a car


' $26.59 per day, plus
' 31 cents per mile
' 3 days and 253 miles
'
LET DAYS = 3
LET MILES = 253
PRINT "Cost is", 26.59 * DAYS + 0.31 * MILES
END

Another Solution
Many other solutions to the above problem are possible. You could have
made the cost a variable:

' Cost of renting a car


' $26.59 per day, plus
' 31 cents per mile
' 3 days and 253 miles
'
LET DAYS = 3
LET MILES = 253
LET COST = 26.59 * DAYS + 0.31 * MILES
PRINT "Cost is", COST
END

This might make the program easier to understand since the calculation is
done in one step and the printing is done is another.

QUESTION 18:

The following version of the program has a bug in it. It prints out

Cost is 0

which is not likely to be the correct answer. Find the bug in the program.

75
' Cost of renting a car
' $26.59 per day, plus
' 31 cents per mile
' 3 days and 253 miles
'
LET DAYS = 3
LET MILES = 253
LET COST = 26.59 * DAYS + 0.31 * MILES
PRINT "Cost is", COSTS
END

Answer:

Since the answer is mysteriously zero, you should suspect that one of the
variable names has been changed. The name COSTS in the PRINT
statement is not the same as COST in the third statement.

' Cost of renting a car


' $26.59 per day
' 31 cents per mile, plus
' 3 days and 253 miles
'
LET DAYS = 3
LET MILES = 253
LET COST = 26.59 * DAYS + 0.31 * MILES
PRINT "Cost is", COSTS
END ^
wrong

Changing the Contents of a Variable


Remember that a variable is a small amount of computer memory that has
been given name. The contents of computer memory can be changed. In your
program you can do this by using a LET statement with a variable that already
has something in it. Look at the following program:

' Changing the contents of a variable


'
LET NUMBER = 23.5 ' create NUMBER, put 23.5 into it
PRINT "First", NUMBER ' look in NUMBER to find a value to
print
LET NUMBER = 45.1 ' put 45.1 into NUMBER (erasing the
23.5)
PRINT "Second", NUMBER ' look in NUMBER to find a value to
print
END

76
Execution starts with the first statement, the first LET statement. This is the
first time NUMBER is used, so memory is found for it. Then 23.5 is put into
it. into it:

NUMBER

23.5

Now the first PRINT statement executes. It looks into NUMBER, finds
23.5, and prints that to the screen. The value in NUMBER has not changed.

QUESTION 19:

Does a LET statement always find new memory for a variable?

Answer:

No. Memory is found for a variable the first time it is used in a statement.

Second LET Statement


The second LET statement changes the contents of the variable.

LET NUMBER = 45.1 ' put 45.1 into NUMBER (erasing the
23.5)

• Sincethe variable NUMBER already exists, no new memory is


found for it.
• The value 45.1 replaces the previous contents of NUMBER.

If you think of a variable as a box, the box can only hold one thing. So after
the second LET statement:

NUMBER

45.1

77
Now the second PRINT statement executes. It looks into NUMBER, finds
45.1, and prints that to the screen. The PRINT statement does not change
the contents of NUMBER.

QUESTION 20:

Look again at the complete program:

' Changing the contents of a variable


'
LET NUMBER = 23.5 ' create NUMBER, put 23.5 into it
PRINT "First", NUMBER ' look in NUMBER to find a value to
print
LET NUMBER = 45.1 ' put 45.1 into NUMBER (erasing the
23.5)
PRINT "Second", NUMBER ' look in NUMBER to find a value to
print
END

What do you expect will be printed to the screen?

Answer:

First 23.5
Second 45.1

Replacing a Variable's Contents


with a Result
The contents of a variable can come from the result of a calculation. You can
use a result to replace the contents of a variable. Look at the following
program:

' Which earns the most money?


' 40 hours at $5 an hour, or
' 30 hours at $6 an hour
'
LET RATE = 5
LET HOURS = 40
LET PAY = HOURS * RATE
PRINT "Pay for ", HOURS, "hours at ", RATE, " = " , PAY
'
LET RATE = 6
LET HOURS = 30
LET PAY = HOURS * RATE
PRINT "Pay for ", HOURS, "hours at ", RATE, " = " , PAY
'

78
END

Here is how the first half of the program works:

1. Memory is found for RATE, and 5 is stored there.


2. Memory is found for HOURS, and 40 is stored there.
3. The third LET statement:
o Finds memory for PAY.
o Uses the value 40 in HOURS.
o Uses the value 5 in RATE.
o Performs the calculation 40 * 5.
o Stores the result, 200, in PAY.
4. The PRINT statement:
o Writes Pay for
o Looks in HOURS, gets the 40, and writes it.
o Writes hours at
o Looks in RATE, gets the 5, and writes it.
o Writes =.
o Looks in PAY, gets 200, and writes it.

At this point computer memory looks like:

RATE HOURS PAY

5 40 200

QUESTION 21:

What does the first half of the program print to the screen?

Answer:

Pay for 40 hours at 5 = 200

Second Half of the Program


The second half of the program is similar to the first. It re-uses the variables
that the first half created:

79
' Which earns the most money? 40 hours at $5 an hour
' or 30 hours at $6 an hour
'
LET RATE = 5
LET HOURS = 40
LET PAY = HOURS * RATE
PRINT "Pay for ", HOURS, "hours at ", RATE, " = " , PAY
'
LET RATE = 6
LET HOURS = 30
LET PAY = HOURS * RATE
PRINT "Pay for ", HOURS, "hours at ", RATE, " = " , PAY
'
END

Here is how the second half of the program works:

1. The value in RATE is replaced with 6.


2. The value in HOURS is replaced with 30
3. The LET statement:
o Uses the value 30 in HOURS.
o Uses the value 6 in RATE .
o Performs the calculation 30 * 6
o Stores the result, 180, in PAY .
4. The PRINT statement:
o Writes Pay for
o Looks in HOURS, gets the 30, and writes it
o Writes hours at
o Looks in RATE , gets the 6, and writes it.
o Writes =
o Looks in PAY, gets 180, and writes it.

QUESTION 22:

What does the complete program print to the screen?

Answer:

Pay for 40 hours at 5 = 200


Pay for 30 hours at 6 = 180

80
Variable's Contents Replaced Many
Times
The contents of a variable can be replaced many times. Examine the following
program:

' Changing the contents of VALUE


'
LET VALUE = 1
PRINT VALUE
LET VALUE = 2
PRINT VALUE
LET VALUE = 3
PRINT VALUE
END

QUESTION 23:

What will the program write to the monitor?

Answer:

1
2
3

Three Steps of a LET Statement


A LET statement can do quite a bit of work. You have seen examples of this
already. Consider this statement:

LET SUM = A + 23.

Here is a summary of what can happen:

A LET Statement

1. Finds memory for each new variable in the statement. A zero


will be placed in numeric variables if there is no other information. (If
there are no new variables, this step does nothing.)
2. Does the calculation on the right of the equal sign. (If there is
nothing to calculate, it just uses the value that is there.)
3. Replaces the contents of the variable to the left of the equal sign
with the result of the calculation.

81
The calculation on the right of the equal sign is carried out just as for any
arithmetic expression. To get that value you can (temporarily) forget that it is
part of a LET statement.

Once a value is "in hand" it replaces the contents of the variable to the left of
the equal sign. There should only be one variable there.

QUESTION 24:

What does the following program print?


' LET example
'
LET A = 2
LET B = 4
LET C = (A + B) / 2
PRINT A, B, C
END

Answer:

2 4 3

Example Explained
Here (again) is what a LET statement does:

1. Finds memory for each new variable in the statement. A


zero will be placed in numeric variables if there is no other
information. (If there are no new variables, this step does
nothing.)
2. Does the calculation on the right of the equal sign. (If
there is nothing to calculate, it just uses the value that is there.)
3. Replaces the contents of the variable to the left of the
equal sign with the result of the calculation.

Here (again) is the example program:

' LET example


LET A = 2
LET B = 4
LET C = (A + B) / 2
PRINT A, B, C
END

The first statement:

82
1. Finds memory for A.
2. Uses the value 2.
3. Stores the 2 in A.

The second statement:

1. Finds memory for B.


2. Uses the value 4.
3. Stores the 4 in B.

The third statement:

1. Finds memory for C. (A and B need no new memory.)


2. Does the calculation: (A + B) / 2
3. Stores the result 3 in C.

Finally the PRINT looks in each of A, B, C and writes out the contents.

QUESTION 25:

Say that the first time a variable appears in a program is on the RIGHT side of
an = sign in a LET statement. Is this a bug?

Say that the first time a variable appears in a program is on the RIGHT side
of an = sign in a LET statement. Is this a bug?

Answer:

Yes, most likely it is a bug. Memory will be found for the new variable, and it
will be set to zero. Usually this is a mistake.

End of the Chapter


Chapter 4

The INPUT Statement


In this chapter you will learn about the QBasic INPUT statement. The
INPUT statement gets data from the computer keyboard.
Chapter Topics

83
• Input and Output in a computer system.
• INPUT statement.
• Prompting the user.
• Entering number data.
• Using several INPUT statements.

Up until now in these notes, all the data a program uses have been part of the
program itself. For example:

' Calculate Miles per Gallon


'
LET MILES = 45678.3 - 45149.6
LET GALLONS = 12.5
PRINT MILES / GALLONS
END

The data is the first odometer reading (45149.6), the second odometer
reading (45678.3), and the number of gallons.

QUESTION 1:

Will this program do the same thing each time it is run?

Answer:

Yes.

Input Devices
Consider the program.

LET MILES = 45678.3 - 45149.6


LET GALLONS = 12.5
PRINT MILES / GALLONS
END

Every time you run the program it will do exactly the same thing. The next
time you fill up your gas tank again, you would have to change the program to
calculate with the new values. The program is not very useful.

Most useful computer programs input data from various sources when they
run. Input means data that comes from outside the program. A program that
does this can work with new data each time it is run.

Sources of Input Data

84
• the keyboard
• a hard disk
• a floppy disk
• a CD-ROM
• the mouse
• a video camera
• an audio digitizer (part of a sound board)
• the Internet
• hundreds of other sources

For us, most data will come from the user of a program typing on the
keyboard. Some sources of data (like audio data) require special hardware. A
piece of hardware that is a source of input to a computer program is called an
input device.

QUESTION 2:

Pac-man was once a popular game found in video arcades. The game was
really a computer program controlling the picture on the video screen. Think of
several types of input data that the program used.

As they run, most computer programs output data to various places. In


programming, output means data that the program sends outside of itself to a
some device. For us, output mostly will go to the computer monitor.

Output can be sent to:

• the monitor
• a hard disk
• a diskette (floppy disk)
• the printer
• a sound board
• the Internet
• hundreds of other places

A piece of hardware that uses data from program is called an output device.

QUESTION 3:

Some devices on the list of input devices and on the list of output devices.
What were some of these devices?

Answer:

• a hard disk
85
• a diskette
• the Internet

I/O
The hard disk of a computer system is used for both input to a program and
output from a program. Other devices are exclusively input devices (such as
the keyboard or mouse) or output devices (such as the printer and monitor.)

Input and Output are so important to a computer system that the abbreviation
I/O is used. Any device which does either input, output, or both is called an
I/O device. The movement of data from or to such a device is often called
"I/O".

QUESTION 4:

Which of the following are NOT I/O devices?

• the keyboard.
• a CD-ROM reader
• the CPU
• the power supply
• the printer cable.
• a floppy disk drive.

Answer:

• the keyboard --- an I/O device (even though it is just input)


• a CD-ROM reader --- an I/O device (even though it is just input)
• the CPU --- NOT an I/O device
• the power supply --- NOT an I/O device
• the printer cable --- NOT an I/O device
• a floppy disk drive --- an I/O device

Notice that the CPU is not an I/O device. It constantly deals with data as it
follows the instructions of your program, but is not a source of data for your
program nor a destination of data from your program.

The INPUT Statement

86
QBasic uses the INPUT statement to input data from the keyboard. Here is
a program that asks the user for a number, then prints out that number times
two:

' Double a Number


'
PRINT "Type a number" 'Ask the user for a number
INPUT NUMBER 'Get it from the keyboard, put it
in NUMBER
PRINT NUMBER * 2 'Print the number times two.
END

Here is how this program looks in the QBasic window:

These statements will execute one by one in sequence. To run the program
push "shift-F5" or use the menu "alt-R, S" (as usual).

QUESTION 5:

What is the first thing the program writes to the monitor

Answer:

Type a number

Running the Program


The first statement is an ordinary PRINT statement that writes a string to the
monitor.

' Double a Number


'
PRINT "Type a number" 'Ask the user for a number
INPUT NUMBER 'Get it from the keyboard, put it
in NUMBER
PRINT NUMBER * 2 'Print the number times two.
END

87
Now the second statement INPUT NUMBER executes. The INPUT
statement is used to get data from the keyboard. It will:

• Printa question mark "?" to the screen.


• Wait until the user has typed in a number.
• Get the number when the user hits the "enter" key.
• Put the number in the variable NUMBER.

Just after this statement starts the monitor will look something like:

Type a number
?

The question mark came from the INPUT statement. The INPUT
statement is waiting for the user (you) to type a number. Say that you type 23.
Now the monitor looks like:

Type a number
? 23

To enter the number, hit the enter key. The


INPUT statement puts the 23
into the variable NUMBER. Next, the PRINT statement executes.

QUESTION 6:

What will the monitor finally look like?

Answer:

The program has done both output and input. It output data to the monitor
when it wrote "Type a number" and the "?". It did input from the keyboard
when it got the 23 and stored it in NUMBER. Then it did output again when it
wrote 46 to the monitor.

88
Now hit any key on the keyboard to switch back to the QBasic window from
the DOS window.

Several Runs of the Program


You can run the program again, without making any change to it. (Push "shift-
F5" to start each run.) You can enter different data for each run. Here is an
example of three runs of the program:

After each run of the program, push any key to return to the QBasic screen.
The picture shows the DOS window after the program was run three times.

QUESTION 7:

Does the program work with floating point numbers?

Answer:

Yes. Floating point numbers are those with a decimal point, such as in the
second run of the program. The variable NUMBER can hold floating point
values.

Variables with INPUT


The INPUT statement must use a variable as a place to put the data it gets.
Remember that a variable is a small amount of computer memory that has
been given name. There is nothing special about the variable used with
INPUT. Here is the same program as before, except that it uses a different
variable name. It will do exactly the same thing as the first version.
89
' Double a Number
PRINT "Type a number" 'Ask the user for a number
INPUT MyData 'Get it from the keyboard, put it
in MyData
PRINT MyData * 2 'Print twice the number.
END

The variable should be the correct type for the expected input. Remember
(from chapter 3) that the last character of a variable name indicates what the
variable is expected to hold. For example, a variable VALUE# can
potentially hold a very big floating point number. A variable DATA% is
expected to hold an integer (no decimal point). Here is a program that does
input of an integer:

' Integer Input


PRINT "Type an integer" 'Ask the user for an integer
INPUT DATA% 'Get it from the keyboard, put it
in DATA%
PRINT DATA% * 2 'Print twice the number.
END

QUESTION 8:

Say that the user types 1.2 when the INPUT statement of this program
asks for data. What will the monitor show after the user hits "enter"?

Answer:

Type a number
? 1.2
2

The variable DATA% can only hold an integer, which can not have a
decimal point. The user typed 1.2, but only the 1 was put into the variable.
(The 1.2 is said to have been truncated to 1). The 1 was then doubled, and 2
was output.

Nice Variable Names


For these notes, programs will mostly use ordinary variables like NUMBER
that do not have a special character at the end of their name. These variables
can hold a useful range of floating point numbers. If you enter a number like

90
"1" (which you might think is an integer) the number is stored in the variable
as "1.0" which is really the same thing. This avoids problems like the above.

Usually a program is written to solve a problem dealing with things in the


world. Numbers are input to the program that describe real things. It is very
useful to use variable names that describe what the numbers mean.

Here is a program that asks the user for the number of fluid ounces and
calculates the number of gallons. Notice how the names of the variables make
it much easier to see what is going on:

' Convert Fluid ounces to Gallons


'
PRINT "Enter number of fluid ounces"
INPUT OUNCES
PRINT "Number of gallons:", OUNCES / 128
END

QUESTION 9:

Write a program that asks the user for the number of grams and prints the
number of kilograms. There are 1000 grams per kilogram. Use the above
program as a model.

(Write this program with paper and pencil, or just "think" it. The best thing to
do would be to use QBasic to write the program and run it before you go on.)

Answer:

' Convert grams to kilograms


'
PRINT "Enter number of grams"
INPUT GRAMS
PRINT "Number of kilograms:", GRAMS / 1000
END

Since each kilogram is 1000 grams, the number of grams is divided by 1000
to get the number of kilograms.

Prompting the User


Say the above program were run and that the user entered 734 grams. The
monitor would look like:

Enter number of grams

91
? 734
Number of kilograms: 0.734

The string "Enter number of grams" is called a prompt. A prompt is a short


phrase which tells the user of a computer program what is expected. The
program is said to prompt the user for input.

You should be careful that the prompt makes sense to the user of a program.
The prompt is for the user; it doesn't "tell" the INPUT statement what to do.
Here is a poorly written version of the "grams to kilograms" program:

' Convert grams to kilograms


PRINT "Enter number"
INPUT GRAMS
PRINT "result:", GRAMS / 1000
END

When this program is run, and the user enters data as before, the user sees:

Enter number
? 734
result: 0.734

The answer is correct, and Mr. Spock might be happy with the program (since
"logically" the two programs are the same). But the second version is not
user-friendly and is prone to user error. Maybe the user though the program
was converting ounces to pounds. Nothing on the monitor would correct this
mistaken notion.

QUESTION 10:

Write a program which converts OUNCES to POUNDS. The program should


write an informative prompt to the user, INPUT the number of ounces, then
write the number of pounds.

Answer:

' Convert ounces to pounds


PRINT "Enter number of ounces"
INPUT OUNCES
PRINT "Number of pounds:", OUNCES / 16
END

Mistakes in Typing Data


92
When an INPUT statement asks for a number, it will reject an unacceptable
number and ask that you type it again. This can get confusing unless you look
carefully at what happens. Say that the above program is run and that the
INPUT statement has asked for a number. The user has typed "rats" but
has not yet hit enter.

Enter number of ounces


? rats

"rats" is not acceptable when INPUT expects a number. When the user hits
enter, the following will appear:

Enter number of ounces


? rats

Redo from start


? _

The INPUT statement did not accept "rats" and so writes the prompt "Redo
from start" and then writes the "?" as usual. Notice that the program is "stuck"
on the INPUT statement. It won't do the PRINT statement (or any other)
again, so you won't see the "Enter number of ounces" prompt again. Now say
that the user enters an acceptable value:

Enter number of ounces


? rats

Redo from start


? 12
Number of pounds .75

Once the INPUT statement gets an acceptable number, it continues as


usual by putting the number in the variable. The rest of the program executes
as usual.

An "acceptable number" means something you typed that looks like a


number. The number might be incorrect data. The INPUT statement does
not know when it is given incorrect data.

QUESTION 11:

Here again is the program to convert ounces to pounds:

' Convert ounces to pounds


PRINT "Enter number of ounces"
INPUT OUNCES

93
PRINT "Number of pounds:", OUNCES / 16
END

The user types the weight in ounces of a newborn baby boy expecting to get
the weight in pounds.

Enter number of ounces


? 640

What will the program do?

Answer:

The program will proceed normally. Newborn babies don't weigh 640 ounces
so this is mistaken data. But it is an acceptable number as far as the
INPUT statement is concerned so it continues without complaint:
Enter number of ounces
? 640
Number of pounds 40

Informative Prompts
The INPUT statement just looks for a number; it does not know what the
number is supposed to mean. It is up to the user to be sure it is the number
wanted. Part of the reason for having informative prompts is to tell the user
what data is expected.

Once a program is given data, it just mechanically plods along doing exactly
what the statements of the program tell it to do. If the input values are not
correct, then it will proceed step by step and produce a result that is not
correct.

The phrase "Garbage In, Garbage Out" is a reminder that a computed result
is only correct if the input data is correct.

In the past, it was common for people to think that computers were "giant
brains" and that everything that came out of them was perfect. Most people
know better, now.

QUESTION 12:

94
The INPUT statement keeps working until you have entered an acceptable
number. When you see the prompt "Redo from start" what do you think it
means?

• re-type every number from the start of the program.


• re-type the number for this INPUT statement.

Answer:

re-type the number for this INPUT statement.

Several INPUT Statements


Often a program needs several values from the user. There are several ways
this can be done. A good way is to prompt and input the values one by one.

The following program calculates the cost of a phone call. The user enters the
number of minutes of the call and the cost per minute.

' Cost of a phone call


'
PRINT "Enter number of minutes"
INPUT MINUTES

PRINT "Enter cents per minute"


INPUT RATE

PRINT "Cost of the call in dollars:", MINUTES*RATE/100


END

Blank lines have been put in the program to make its operation more clear.
The blank lines are just skipped (like comments) when the program runs.

When this program is run, the first PRINT statement will prompt the user.
Then the first INPUT statement will get a number from the user and put it in
MINUTES:

Enter number of minutes


? 23

Now the next PRINT statement will prompt the user and the next INPUT
statement will get the value and put it in RATE:

95
Enter number of minutes
? 23
Enter cents per minute
? 10

Finally the last PRINT statement will perform the calculation using the
numbers in the two variables, and print the result to the screen:

Enter number of minutes


? 23
Enter cents per minute
? 10
Cost of the call in dollars: 2.30

QUESTION 13:

Write a program that asks the user for the number of kilowatt-hours of
electricity used and asks for the cost in dollars of each kilowatt-hour. The
program will calculate the cost of the electricity.

Answer:

' Cost of electricity


'
PRINT "Enter number of kilowatt-hours"
INPUT KWH

PRINT "Enter dollars per kilowatt-hour"


INPUT RATE

PRINT "Cost in dollars:", KWH * RATE


END

More Mistakes
A program executes statements one at a time in sequence. If an INPUT
statement is waiting for you to type a number, no other statement will execute
until this has happened.

Say that the above program is running, and that you have correctly typed in
the first number but have incorrectly typed in the second number, as below:

Enter number of kilowatt-hours


? 1294
Enter dollars per kilowatt-hour
? $0.096480

96
Redo from start
? _

The second number is incorrect because the "$" can not be part of a number.

QUESTION 14:

What should the user type now so that the program will continue?

Answer:

? 0.096480

The dollar sign "$" was not typed this time so the program can input the
number and continue:

? 0.096480
Cost in dollars: 124.8451

Restaurant Calculator
Here is a longer program. It asks the user for the total restaurant bill before
tax. Then it asks for the amount of tax. Finally it calculates and prints the
amount of money to pay including a 15% tip. The tip is calculated on the total
before tax.

' Restaurant Bill calculator


'
PRINT "Enter the total before tax:"
INPUT TOTAL

PRINT "Enter the amount of tax:"


INPUT TAX

LET TIP = TOTAL * 0.15


PRINT "Please pay:", TOTAL + TAX + TIP
END

QUESTION 15:

Modify the program so that it writes out the amount of the TIP in addition to
writing the total amount to pay.

Answer:

97
' Improved Restaurant Bill calculator
'
PRINT "Enter the total before tax:"
INPUT TOTAL

PRINT "Enter the amount of tax:"


INPUT TAX

LET TIP = TOTAL * 0.15


PRINT "The tip is:", TIP
PRINT "Please pay:", TOTAL + TAX + TIP
END

The addition of a new PRINT statement makes the output more


informative.

Improving the Bill Calculator


Say that the amount of sales tax is always 5% of the total before tax. The
program could be improved by asking the user for just one value and using
just one INPUT statement.

QUESTION 16:

If the program has just one INPUT statement, what value will be input?

Answer:

If the tax is always 5% of the TOTAL, only TOTAL is needed for input.

Complicated Billing
Here is the new version of the program:

' Improved Restaurant Bill calculator


'
PRINT "Enter the total before tax:"
INPUT TOTAL

LET TAX = TOTAL * 0.05 ' 5 percent tax


LET TIP = TOTAL * 0.15

PRINT "The tax is:", TAX


PRINT "The tip is:", TIP

98
PRINT "Please pay:", TOTAL + TAX + TIP
END

(The tax on a restaurant bill in a big city can be more complicated than a
percentage of the total. The previous version of the program might actually be
more practical.)

Billing can get complicated. Consider a photocopy shop that has the following
charges:

• $0.05 to photocopy one page.


• $0.03 per staple.
• 5% tax on the total.

Say that you want to make several copies of a booklet. The booklet has a
number of pages held together with one staple.

QUESTION 17:

Think about writing a program that will calculate the cost of making a given
number of booklets. What two numbers do you think should be INPUT?

Answer:

You want to input the number of PAGES per booklet and the number of
COPIES. If these numbers are input, the program can calculate the total
number of pages and the number of staples and from those calculate the total
cost.

Billing Program
Remember the cost for making booklets:

• $0.05 a page
• $0.03 per staple
• 5% tax on the total.

Here is a program that asks for the number of pages and asks for the number
of copies. It then calculates and prints the total cost.

' Copy Cost Calculator

99
'
PRINT "Enter the number of pages:"
INPUT PAGES

PRINT "Enter the number of copies:"


INPUT COPIES

LET STAPLECOST = COPIES * 0.03


LET PAGECOST = PAGES * COPIES * 0.05
LET TOTAL = STAPLECOST + PAGECOST
LET TAX = TOTAL * 0.05

PRINT "The total is:", TOTAL


PRINT "The tax is:", TAX
PRINT "The grand total is:", TOTAL + TAX
END

QUESTION 18:

Look at the statement

LET PAGECOST = PAGES * COPIES * 0.05

Why does it calculate the cost for making all the photocopies needed?

Answer:

There are going to be COPIES number of booklets. Each booklet will have
PAGES number of pages in it. So the total number of photocopies made will
be PAGES * COPIES. It costs $0.05 for each photocopy. So the cost for
photocopies will be caclulated by:

LET PAGECOST = PAGES * COPIES * 0.05

End of the Chapter


Chapter 5

Beginning Graphics
Up until now, our programs did output by printing characters to the monitor.
Programs can also output graphics to the monitor. This chapter discusses
ways to draw simple pictures on the monitor screen.

Chapter Topics:

100
• SCREEN statement
• COLOR statement

• PSET statement

• LINE statement
• The graphics screen
• Pixels
• Arithmetic and graphics
• Variables and graphics
• CIRCLE statement
• INPUT and graphics

Different computers have different graphics hardware. Electronic signals must


be sent to this hardware to start it going before your program can do graphics.
The QBasic statement that starts up graphics is:

SCREEN 12

This SCREEN statement says we want to use graphics in "mode 12." There
are about 13 modes. Most modes are for older computers and are of no
interest to us.

QUESTION 1:

Do you think that your computer has graphics hardware?

Do you think that your computer has graphics hardware?

Answer:

Yes. All modern desktop computers have graphics hardware.

SCREEN Statement
Read this entire page before entering and running the example program.

A program must have a SCREEN statement before it does any graphics. A


computer that is more than fifteen years old might need to use one of the
older SCREEN modes. We will always use SCREEN 12. Here is a graphics
program which puts one spot on the monitor screen. To be safe, close down
any other programs you have running on your computer before you run this
one.

101
'Put a spot on the screen at column 30 row 50
SCREEN 12
PSET (30, 50)
END

When you run the program, the QBasic system starts up the graphics
hardware and a graphics screen will appear on your monitor. This screen is
a temporary replacement for the screen that you usually see on your monitor.
You should see a small spot close to the upper left of the monitor screen.

The monitor screen will be filled with the graphics screen. (The above image
is smaller than the graphics screen you will see.) At the bottom of the screen
you should see the prompt:

Hit any key to continue

Hit some key (like "enter") and you will go back to the QBasic screen which
shows your program. However, the QBasic screen will now completely fill
the monitor screen.

To return to the normal Screen:

To get back to the usual situation where QBasic fills just one window on the
screen, do this:

1. Press and hold down the keys <alt><enter> (press the "Alt"
key, keep holding it down, and press the "enter" key).
2. You should be back to the normal screen. If not, click the mouse
in the screen and repeat <alt><enter>.

This is an awkward procedure, so practice it a few times before you enter long
programs.

QUESTION 2:

What is wrong with the following program?


'Put a spot on the screen at column 30 row 50
PSET (30, 50)
SCREEN 12
END

102
Answer:

The SCREEN statement must be before any graphics statement. If you run
the program:

'Put a spot on the screen at column 30 row 50


PSET (30, 50)
SCREEN 12
END

you will get an error message:

Illegal Function Call

This means that since you did not start graphics first, the QBasic system can't
do the PSET statement.

PSET
Here is the correct version of the program:

'Put a spot on the screen at column 30, row 50


SCREEN 12
PSET (30, 50)
END

The SCREEN statement starts up the graphics hardware so that now other
graphics statements can be done.

The PSET statement stands for Pixel Set. A pixel is a dot on a computer
graphics screen. Pixel stands for picture element. "Set" means to "turn on," so
this statement turns on one dot on the screen. All computer graphics pictures
are made of thousands of pixels. The PSET statement looks like this:

PSET (column, row)

Column and row can be numbers or variables. The part of the statement
(column, row) says where on the graphics screen to set the pixel.

QUESTION 3:

103
Look at the following piece of graph paper. What is the column and row
number of the square with the X?

Answer:

The square with the X is column 5 row 3.

Columns and Rows


Here is that graph paper again, now with more squares marked:

104
The position of each square is given by its column number and row number.
For instance, the square with the # is column=1 row=5. The square with the $
is column=5 row=1. Notice that you have to be careful to get column and row
in the right order.

QUESTION 4:

What is the column and row of the square marked with ? ?

Answer:

Column 8, Row 4.

X and Y
People usually talk about places on the computer graphics screen as "X and
Y" rather than "column and row."

Here is the graph paper again, but now the sides are labeled "X" and "Y":

X starts at zero on the left and increases to the right. Y starts at zero at the
top and increases going down (this is unlike graphs in math books where Y
usually increases going up).

QUESTION 5:

What are the X and Y values of the squares marked with *, #, $, and ?

105
Chapter 6

>..............................................................

How to Download and Install QBasic

You may already have QBasic on your system. See Chapter 0 on how to check if this
is so.
The following steps should work on any recent Microsoft operating system.

Step 1. Create a Subdirectory for QBasic


Create a subdirectory to contain QBasic. Call the subdirectory olddos (or any other
name that you like). Typically this directory is put in the C:\ disk.
Use whatever method you prefer to create this subdirectory. Here is a way that uses
the command prompt window:
1A. On your desktop, click on "Start"

1B. Click on Run. Then in the Run dialog box type CMD and click on OK.

106
A DOS window (sometimes called a command prompt window) starts up:

1C. Change the directory to the root directory of C: (or any other disk) by using the
CD command followed by a backslash:

1D. Now make a new directory under C: by using the MKDIR command:

107
If you want, you can change to the new directory by using the CD command, and then
list out the files in this directory with the DIR command. There will be no files (yet)
in this directory.

Step 2. Download OLDDOS


2A. With your Web browser, go to the site:
http://support.microsoft.com/kb/135315

Scroll down to nearly the bottom of the page until you see Download Olddos.exe
now.

108
2B. Click on: Download Olddos.exe now. An alert window will pop up.
2C. Click the button "Save File". (Different operatings systems have different
windows, here.)
2D. Click on OK.

2E. A "Save As" dialog appears:

109
2F. Navigate to the subdirectory that you created in Step 1, C:\olddos.
2G. Click on "Open". Click Save. The File Download dialog shows the progress.

When the download is done, the dialog title changes to "Download complete".

2H. Click Close.

110
Step 3. Unpack the OLDDOS Files
3A. Go back to the DOS window of Step 1 (or start a new one and change its default
directory to the directory where you put OLDDOS.EXE.)
3B. Enter the command DIR to see the files in the subdirectory.

The file OLDDOS.EXE should be there.


3C. At the command prompt, type olddos.exe

3D. Answer the question "Do you want to extract these files now" by typing "y".

111
A long list of files is extracted and left in your subdirectory. QBasic is contained in
the two files QBASIC.EXE and QBASIC.HLP. You could delete all the other files
but these, but it does not hurt to keep them. (If you keep OLDDOS.EXE you will
have all the files in compact form.)
At this point, QBasic is on your computer.
3E. To confirm that it works, type qbasic in the DOS window. (The working
directory should be the directory that now holds QBASIC.EXE.) The window will be
filled with the QBasic system:

3F. For now, just exit QBasic by typing "escape" then "alt" and then "f".

112
3G. Push the down arrow on your keyboard until "Exit" is highlighted, and then hit
"enter". You will return to the DOS prompt.
(Note: you will not be able to use your mouse to make slections by clicking on words
and icons within the QBasic window. To make selections from the menu, use the
"Alt" key, and then use the arrow keys to change the selection. Another way to do this
is to hit "Alt" and then use the first letter of the menu selection you want.)

Step 4. Change the PATH Variable


At this point, you could run QBasic by starting a DOS window, changing to the
subdirectory that holds QBASIC.EXE, and typing "qbasic" at the command prompt. But
it is more convenient to be able to run QBasic from any subdirectory.
For Windows 98/2000:
4A. Click Start. Select Settings/Control Panel.

4B. In Control Panel double click on System.


4C. In System Properties, click on Advanced:

113
4D. Then click on Environment Variables:

4E. Click on "Path" under "System variables".


4F. Then Click the "Edit" button just below it. The new dialog shows "Path" in the
Variable Name box, and a list of things in the Variable Value box.
4G. At the end of whatever is there, type a semicolon followed by the pathname of the
directory where QBASIC.EXE is located:
;C:\olddos

114
4H. Click OK.
4I. In Environment Variables, click OK.
4J. In System Properties, click OK.
Now you should be able to start QBasic from any DOS window merely by typing
qbasic at the command prompt.
You are done installing QBasic.

>...................................

1. How to Start QBasic


This method uses the DOS window, similar to what is done in Appendix A. There are
other ways to do this using the windows interface. You can navigate with Windows
Navigator to the directory that holds qbasic.exe and click on it to start it.
1A. On your desktop, click on "Start"

1B. Click on Run. Then in the Run dialog box type CMD and click on OK.

115
A DOS window (sometimes called a command prompt window) starts up. When it
first starts, it will be set up to use a particular part of the hard disk for the QBasic files
it may save and read. This is called the default directory. If you are not going to save
your program files to the hard disk skip to 1F. If you want to save programs to the
hard disk, do the optional steps that follow.

1C. Optional: Change the default directory to the root directory of C: (or any other
disk) by using the CD command followed by a backslash:

1D. Optional: make a new directory to hold your programs. You only need to do this
once. Call the directory QSOURCE (or any other name you like). Use the MKDIR
command:

116
1E. Optional: Change to the directory in which you keep your QBasic source
programs. This might be the directory you just created (in step 1D).

Notice that in the DOS window, uppercase and lower case don't matter. The "change
directory" command is CD or cd. The directory you change to can be in upper or
lower case (or a mix of both).
1F. Start the QBasic system by typing qbasic:

1G. The QBasic development window appears:

117
1H. Hit ESCAPE (tap the Esc key) to clear the welcome message. (Or, you can hit
Enter to explore the on line help of the QBasic system.)

2. How to Create and Run a Program


You may have to left-click the mouse in the QBasic window to give it "focus". The
window has focus when the top bar of the window is light blue, as seen in 1H. There
should also be a yellow underscore blinking in the upper left.
(Note: you will not be able to use your mouse to make selections by clicking on words
and icons within the QBasic window. To make selections from the menu, use the
"Alt" key followed by the first letter of the menu. Or you can use the arrow keys to
change the menu selection. Hit enter to make a selection. Hit Escape to undo a choice.
Hit tab to move among choices in a dialog box.)

118
(The above may sound really awful. But it is easy after you have done it a few times.)
2A. Enter you program by typing on the keyboard. The characters should appear in
the window. The example program is:
PRINT "Hello"
END
If you type "print" in lower case, the QBasic system will automatically change it to
upper case.
If you make mistakes, use the arrow keys on the keyboard to move the cursor (the
yellow underscore) to the mistake.
Use the delete (Del) key or the backspace key to remove the mistake and enter the
correct characters.

If the system is confused (and does not accept characters or starts showing menus you
don't want) hit the Escape key. You may need to do this in the steps that follow, too.
2B. Run the program by tapping the F5 key (on the top row of the keyboard). The
program starts executing statements one by one starting with the first statement. This
program prints "Hello" to the screen:

119
2C. Hit the Enter key (or any other) to return to the QBasic window

2D. (Alternative) Run the program by using the menu system. Tap the Alt key on the
keyboard. The first letter of every command on the menu bar should now be white (as
seen in 2C, above). Tap the R key. The Run menu will appear:

120
2E. (Alternative) Hit the S key (or just hit Enter) to run the program. The menu
shows shortcuts to do the same thing, Shift+F5 or just F5 alone. The program runs:

Since the program was run once before, the first output (the first "Hello") remains on
the screen. Hit return (or any key) to return to the QBasic window (as before).
2F. Debug your program. Typically at this point you will discover that the output is
incorrect. Repeat steps 2A, 2B, and 2C until the program works correctly.
2G. To exit QBasic without saving your program: Click on the small box that
contains an X in the upper right corner of the window.

121
Another way to exit is to use the QBasic menus: hit Alt+F+x . The system will ask
you if you want to save the program, similar to 3B, below.
You know enough now to read the first several chapters of these notes and to play
with their example programs. When you start writing your own programs you will
need to save programs onto your computer's hard disk. The following sections explain
how to do that.

3. How to Save a Program to a Source File


A "source file" is a permanent disk file that contains a program. Unless you save your
program to a file, it will be lost forever when you leave the QBasic system. With a
short program, this might not matter. But if you are creating a program with dozens of
statements you should save it to disk as soon as you can, even before it is completely
working.
3A. Tap the Alt key on the keyboard. The first letter of every command on the menu
bar should now be white (as seen in 2C, above). Now tap the F key to see the File
menu:

122
(In the above picture, the actual program is covered up by the menu.)
3B. Tap the S key for "Save".

3C. Tap the Y key for "Yes".

123
3D. Type "hello.bas" as a file name and tap the RETURN key.

Of course, other programs should be give other file names.


3E. If you try to save the program a file that already exists, the system will ask if you
really want to do this.

124
You should be sure this is what you want to do before you hit Enter (or Y). Otherwise
tap the N key to go back to 3D.
3F. You can keep saving the program to the same disk file (repeatedly updating it as
you make changes) by using the S menu choice. It will not ask you for a new file
name each time. If you want to use a NEW file name, pick the Save As option.

This will bring you back to 3C and you can pick a new name for the file.
3G. Push the down arrow on your keyboard until "Exit" is highlighted, and then hit
"enter". You will return to the DOS prompt.

4. How to Load a Program from a Disk File


You can load QBasic with a program that has been saved as a disk file.

125
4A. Start QBasic (if needed). Open the File menu by hitting Alt+F

4B. Hit the O key. This brings up the open file dialog:

4C. The dialog shows the QBasic files in the default directory. (In the above, the
default directory is C:\QSOURCE). You may see many files in the directory. To
select a file, tap the tab key of your keyboard until the cursor (blinking underscore) is
in the box labeled "Files". (The tab key is the key above the Caps Lock key on the
keyboard.)
Now hit the up and down arrow keys until the file you want is highlighted:

126
(An alternative way is to just type the file name into the "File Name:" box.
4D. Hit the Enter key. The program in the file should appear in the QBasic window
just as it was when you saved it:

5. How to Cut and Paste


Sometimes you have part of a program you would like to copy to another part. Other
times you would like to move a few statements to another part of the program. Cut,
Copy, and Paste from the Edit menu can be used for this.
5A. Highlight the lines you wish to copy (or cut) by moving the cursor to the first
character of the lines. Do this with the arrow keys of the keyboard. The mouse will
not work for this.

127
Now push and hold down the Shift key and move the cursor over the lines you wish to
copy. The lines will be highlighted:

5B. Access the Edit menu by hitting Alt+E. Move the menu selection down to Copy:

Hit Enter.
5C. In the program window, move the cursor to where you wish to paste the line(s)
that were copied.
5D. Return to the Edit menu (Alt+E). Move the selection down to Paste.

128
5E. Hit Enter. The copied line(s) are pasted into the program. You may need to do
some fine adjustment with the arrow keys and the delete key.

6. End
This is the end of this Appendix. There is much more to the QBasic system. Some
topics are covered in the main chapters when they are needed.

129
BASIC, an acronym for Beginner's All-purpose Symbolic Instruction Code, is in a
family of high-level programming languages. The original BASIC was designed
in 1964 by John George Kemeny and Thomas Eugene Kurtz at Dartmouth
College in New Hampshire, USA to provide computer access to non-science
students. At that time, nearly all use of computers required writing custom
software, which was something only scientists and mathematicians tended to be
able to do. BASIC was therefore designed to allow students to write programs for
the Dartmouth Time-Sharing System. It was intended to address the complexity
issues of older languages with a new language design specifically for the new
class of users that time-sharing systems allowed—that is, a less technical user
who did not have the mathematical background of the more traditional users, and
was not interested in acquiring it. Being able to use a computer to support
teaching and research was quite novel at the time. In the following years, as other
dialects of BASIC appeared, Kemeny and Kurtz's original BASIC dialect became
known as Dartmouth BASIC.

The language and its variants became widespread on microcomputers in the late
1970s and 1980s. BASIC remains popular to this day in a handful of highly
modified dialects and new languages influenced by BASIC such as Microsoft
QBASIC which is the language we will use in this course to acquire the intended
basic programming principles and skills.

COMPUTER PROGRAMMING TOOLS

INTRODUCTION TO QBASIC
QBasic is a variant of the BASIC programming language designed by Microsoft
between 1991 and 2000. With QBasic the user can design computer programs
and/or utilities. It is a very popular programming language for beginners. While
its lack of power makes it unsuitable for many of today's applications, it is an
invaluable programming learning tool.

QBasic is both an IDE and interpreter. It was developed based on QuickBasic, a


compiler also developed by Microsoft between 1985 and 1988. NB: An IDE

130
(integrated development environment or integrated design environment or
integrated debugging environment) is anhat provides comprehensive facilities to
computer programmers for software development. An IDE normally consists of: a
source code editor, a compiler and/or an interpreter, build automation tools, and a
debugger.

Code entered into the QBASIC IDE is compiled to an intermediate form, and this
intermediate form is immediately interpreted on demand within the IDE. It can
run under nearly all versions of DOS and Windows, or through
DOSBox/DOSEMU, on Linux and FreeBSD. For its time, QBasic provided a
state-of-the-art IDE, including a debugger with features such as on-the-fly
expression evaluation and code modification.
Like QuickBASIC (a compiler), but unlike earlier versions of Microsoft BASIC,
QBasic is a structured programming language, supporting constructs such as
subroutines and while loops. Line numbers, a concept often associated with BASIC,
are supported for compatibility, but are not considered good programming technique,
having been replaced by descriptive line labels. QBasic has limited support for user-
defined data types (structures), and several primitive types used to contain strings of
text or numeric data.

SUBROUTINES AND FUNCTIONS


Subroutines and functions are ways to break up your code into a reusable form. They
allow the programmer to do a large set of operations just by calling the appropriate
procedure or function. For example, say you need to PRINT a lot of lines, such as
instructions. One way to do this is to just enter all your PRINT commands directly
into where you need them. At some point, you may want to move the PRINT
commands, or you may use the exact set of PRINTs elsewhere in the program. To
move or change all of the PRINT commands would be quite a hassle. A simpler way
would be to create a procedure and enter all of the PRINT commands there; then,
when you need to execute the commands, you may simply call your procedure and it
will execute each line in its body.

Procedure vs. Function


A procedure does something and does not return anything for the programmer. For
example, a procedure might be used to set the screen mode and palette.
A function does something and RETURNS a value. For example, if you need to find
the average of two values, you might write a function that takes in two numbers and
returns the average.

131
APPENDIX A

List of Programming Languages in Alphabetical Order

A
1. A+ 20. ACT-III 41. Arduino
2. A++ 21. Ada 42. Argus
3. A# .NET 22. Adenine 43. ARLA
4. A# (Axiom) 23. Afnix 44. Asp
5. A-0 System 24. Agora 45. Assembly (65x02)
6. ABAP 25. AIS Balise 46. Assembly (65816)
7. ABC 26. Aikido 47. Assembly (68000)
8. ABC ALGOL 27. Alef 48. Assembly (ARM)
9. Abel 28. ALF 49. Assembly (PowerPC)
10. ABLE 29. ALGOL 58 50. Assembly (SPARC)
11. ABSET 30. ALGOL 60 51. Assembly (System
12. ABSYS 31. ALGOL 68 360)
13. Abundance 32. Alice 52. Assembly (Vax
14. ACC 33. Ambi 11/785)
15. Accent 34. Amiga E 53. Assembly (x86/x64)
16. ActForex 35. AMOS 54. ATS
17. Action! 36. AMPLE 55. AutoHotkey
18. ActionScript 37. AngelScript 56. AutoIt
38. APL 57. Averest
19. Ace DASL 39. AppleScript 58. AWK

40. Arc 59. Axum

B
60. B 67. Bertrand 74. Bon
61. Bash 68. BETA 75. Boo
62. BASIC 69. Bigwig 76. Boomerang
63. bc 70. Bistro 77. BPEL
64. BCPL 71. BitC 78. BUGSYS
65. BeanShell 72. BLISS 79. BuildProfessional

66. Batch (Windows/Dos) 73. Blue

132
C
80. C 86. chomski 93. Cola
81. C-- 87. CHR 94. ColdC
82. C++ - ISO/IEC 14882 88. Chrome 95. ColdFusion
83. C# - ISO/IEC 23270 89. ChucK 96. COMAL
84. C/AL 90. CICS 97. Common Lisp (also
85. Caché ObjectScript 91. CIL known as CL)
92. Cilk 98. COMPASS
• Caml 93. CL
• Cat (Honeywell) • Component Pascal
• Cayenne • COMIT
• Cecil • CL (IBM) • Converge
• Cel • Claire • Cool
• Cesil • Clarion • Coral 66
• CFML • Clean • Corn
• Cg • Clipper • CorVision
• Ch interpreter (C/C++ • CLIST • COWSEL
interpreter) • Clojure • CPL
• Chapel • CLU • csh
• CHAIN • CMS-2 • CSP
• Charity • COBOL - • Csound
• Chef ISO/IEC • Curl
• CHILL 1989 • Curry
o Cobol
• CHIP-8 Script • Cyclone
• Cobra

• CODE

D
• D • Datalog • DinkC
• D# • DATATRIEVE • Dialog Manager
• Dao • dBase • DIBOL
• DASL - Distributed • dc • DL/I
Application • DCL • DotLisp
Specification • Deesel (formerly G) • Dylan

133
Language • Delphi • dylan.NET
• DASL - Datapoint's • Dynace
Advanced Systems • Dialect
Language • DYNAMO
• DarkBASIC
• DarkBASIC
Professional

• DataFlex

E
• E • EGL • Escapade
• Ease • Eiffel • Escher
• EASY • Einstein • ESPOL
• Easy PL/I • ELAN • Esterel
• Easycoder • elastiC • Etoys
• EASYTRIEVE • Elf • Euclid
PLUS • Emacs Lisp • Euler
• eC (Ecere C) • Emerald • Euphoria
• ECMAScript (programming • CMS EXEC
• Ecol language)
• eDeveloper • Englesi • EXEC 2
• Epigram
• Edinburgh IMP
• Erlang

F
• F • FL • Forth
• F# • Flavors • Fortran - ISO/IEC
• Factor • Flex 1539
• Falcon • FLOW-MATIC • Fortress
• Fantom • Fly • FoxPro 2
• Felix • FOCAL • FP
• Ferite • FOCUS • Franz Lisp
• FFP • FOIL • Frink
• FILETAB • FORMAC • F-Script
• FormWare
• Fjölnir • Fuxi
• @Formula

G
• Gambas • GM • GOTRAN
• GAMS • GML • GPSS
• GAP • Go • GraphTalk

134
• G-code • Go! • GRASS
• GDL • GOAL • Green
• Gibiane • Gödel
• GJ • Godiva • Groovy

• GLSL • Goo

H
• HAL/S • High Level • Hugo
• IBM HAScript Assembly • Hume
• Haskell • HLSL
• Hop • HyperTalk
• HaXe
• Hope

I
• IBAL • IDL • IPL
• IBM Basic assembly • IMP • IPTSCRAE
language • Inform • IronPython
• IBM Informix-4GL • Io • ISPF
• IBM RPG
• ICI • Ioke • ISWIM
• Icon

• Id

J
• J • Janus • JOSS
• J# • JASS • Joule
• J++ • Java • JOVIAL
• JADE • JavaScript • Joy
• JAGEX • JCL • JScript
• Jako • JEAN • JSP

• JAL • Join Java • JavaFX Script

K
• K • KEE • KRC
• Kaleidoscope • Kiev • KRYPTON
• Karel • KIF • ksh
o Karel++ • Kite
• KUKA
• Kaya • Kogut

135
L
• L • Limbo • Logo
• L# .NET • Limnor • Logtalk
• L++.NET (no longer • LINC • LOTUS
developed) • Lingo • LPC
• LabVIEW • Linoleum • LSE
• Ladder • LIS • LSL
• Lagoona • LISA • Lua
• LANSA • Lisaac • Lucid
• Lasso • Lisp - ISO/IEC • Lush
• Lava 13816 • Lustre
• Leadwerks Script • Lithe • LYaPAS
• Leda • Little b
• Lynx
• Legoscript • Logix

M
• M • MDL • Modula
• M4 • MelloCOMPLEX • Modula-2
• MAD • Mercury • Modula-3
• Magik • Mesa • Mohol,
• Magma • Metafont • Mondrian
• MapBasic • MetaL • MOO
• Maple • Microcode • Mortran
• MAPPER • MicroScript • Moto
(Unisys/Sperry) now • MIIS • Mouse
part of BIS • MillScript • MPD
• MARK-IV • MIMIC • MSIL - deprecated
(Sterling/Informatics • min name for CIL
) now • Mindscript • MSL
VISION:BUILDER • Miranda • MSX BASIC
of CA • MIVA Script • MUMPS
• Mary • ML • Murphy Language
• MASM Microsoft • Moby
Assembly x86 • Mythryl
• Mathematica • Model 204
• MATLAB
• Maxima (see also
Macsyma)
• MaxScript internal
language 3D Studio
Max

• Maya (MEL)
136
N
• Napier88 • NewLISP • Nimrod
• NATURAL • NEWP • Nosica
• NEAT chipset • NewtonScript • NPL
• Neko • NGL • NQC
• Nemerle • Nial • Nu
• NESL • Nice
• Net.Data • NXC
• Nickle
• NetLogo

O
• o:XML • Obliq • OpenEdge ABL
• Oak • Obol • OPL
• Oberon • occam • OpenOffice Basic
• Object Lisp • occam-π • OPS5
• ObjectLOGO • Octave • Orc
• Object Pascal • OmniMark • ORCA/Modula-2
• Objective-C • Onyx • Orwell
• Objective Caml • Oxygene
• Opal
• Objective-J • Oz

P
• PARI/GP • PL-11 • PortablE
• Pascal - ISO 7185 • PL/0 • Powerhouse
• Pawn • PL/B • PowerBuilder - 4GL
• PCASTL • PL/C GUI appl. generator
• PCF • PL/I - ISO from Sybase
• PEARL 6160 • PowerScript
• Perl • PL/M • PPL
o PDL • PL/P • Processing
• PHP • PL/SQL • Prograph
• Phrogram • PL360 • PROIV
• Pico • PLANC • Prolog
• Pict • Plankalkül o Visual Prolog
• Piet • PLEX • Promela
• Pike • PLEXIL • PROTEL
• PIKT • Pliant • Proteus
• PILOT • POP-11 • ProvideX
• Poplog • Pure
• Pizza
• PostScript • Python

137
Q
• Q • QtScript
• QuakeC
• Qi
• QPL

R
• R • REBOL • Rlab
• R++ • Redcode • ROOP
• RAPID • REFAL • RPG
• Rapira • Reia • RPL
• Ratfiv • Revolution • RSL
• Ratfor • rex • Ruby
• RBScript
• REXX • RapidBATCH
• rc

S
• S • Seed7 • SNUSP
• S2 • Self • SOAP
• S3 • SenseTalk • SOL
• S-Lang • SETL • Span
• S-PLUS • Shakespeare • SPARK
• SA-C • Shift Script • Spice
• SAC • SiMPLE • SPIN
• SAIL • SIMPOL • SP/k
• SALSA • Simscape • SPS
• SAM76 • SIMSCRIPT • Squeak
• SAS • Simula • Squirrel
• SASL • Simulink • SR
• Sather • SISAL • SSL
• Sawzall • Slate • Strand
• SBL • SLEEP • Stateflow
• Scala • SLIP • Subtext
• Scheme • SMALL • Suneido
• Scilab • Smalltalk • SuperCollider
• Scratch • SML • SuperTalk
• Script.NET • SNOBOL(SPITBOL) • SYMPL
• Sculptor 4GL • Snow • SyncCharts

• Sed • Snowball • SystemVerilog

T
• T • TELCOMP • Topspeed

138
• TACL • gt-Telon • TPU
• TACPOL • TenCORE • Trac
• TADS • TeX • T-SQL
• TAL • TEX • TTCN
• Tcl • TIE • Turbo Pascal
• Tea • thinBasic • Turing
• TELON - programming • TUTOR
Mainframe Online language
IMS/COBOL • Timber • TXL
Generator • Tom

• TECO • TOM

U
• Ubercode • uniPaaS • Unlambda
• Unicon • UNITY • UnrealScript

• Uniface • Unix shell • USE (Regency


Systems)

V
• Vala • Visual Basic • Visual FoxPro
o Genie • Visual Basic .NET • Visual J++
• VBA • Visual C++ • Visual Objects
• VBScript • Visual C++ .Net
• Verilog • Visual DataFlex • Vvvv

• VHDL • Visual
DialogScript

W
• Water • WebQL • Winbatch

• WATFIV, • Whitespace
WATFOR

X
• X++ • XL • XPL0
• X10 • XOTcl • XQuery
• XBL
• XPL • XSLT - See XPath
• xHarbour

139
Y
• Y • YAL • Yorick

• Yoix

Z
• Z • Zonnon • ZPL
• Z notation • ZZT-oop
• ZOPL
• Zeno

140

Вам также может понравиться