0% found this document useful (0 votes)
138 views

MTH 208-Intro To Comp Programming

This document provides an overview of computer science concepts including definitions of a computer, the history of computers, and generations of computers. It discusses how computers have evolved from early mechanical calculators to the first electronic digital computers using vacuum tubes, to modern transistor-based computers. The first generation used vacuum tubes, punched cards, and magnetic storage. The second generation introduced transistors, assembly languages, stored programs, and high-level languages. The document serves as an introduction to basic computer science topics.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
138 views

MTH 208-Intro To Comp Programming

This document provides an overview of computer science concepts including definitions of a computer, the history of computers, and generations of computers. It discusses how computers have evolved from early mechanical calculators to the first electronic digital computers using vacuum tubes, to modern transistor-based computers. The first generation used vacuum tubes, punched cards, and magnetic storage. The second generation introduced transistors, assembly languages, stored programs, and high-level languages. The document serves as an introduction to basic computer science topics.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

MTH 208

Introduction to Computer Programming


Using

QBASIC
REM IF….THEN GOTO LET WHILE…..DO

UNIVERSITY MAIDUGURI
(FACULTY OF SCIENCE)
Department Mathematical Sciences

Prepared By:
Abdullahi Isa & Ali Baba Dauda 1|
Module One:
Definitions, History, Overview of Computing and Computer Science.

Module Two:
Component of Computer System and Applications of Computer System.
Advantages and Disadvantages of Computer System.

Module Three:
Problem Solving with Flowcharts, Algorithms and Data Presentations

Module Four:
BASIC Programming

2|
MODULE ONE
DEFINITIONS, HISTORY, OVERVIEW OF COMPUTING AND COMPUTER
SCIENCE

REVIEW OF BASIC CONCEPTS IN COMPUTER SCIENCE

Introduction to Computer

This lecture focuses on basic definitions of computer, history of computer, generations of


computer, classification of computer, basic elements of computer system.

Introduction to Computer

Today, almost all of us in the world make use of computers in one way or the other. It finds
applications in various fields of engineering, medicine, commercial, research and others. Not only
in these sophisticated areas, but also in our daily lives, computers have become indispensable.
They are present everywhere, in all the devices that we use daily like cars, games, washing
machines, microwaves etc. and in day to day computations like banking, reservations, electronic
mails, internet and many more.

What is Computer?

A computer is an electronic device, operating under the control of instructions stored in its own
memory that can accept data (input), process the data according to specified rules, produce
information (output), and store the information for future use.

In other word, Computer is a device or set of devices that work under the control of a stored
program, automatically accepts and processes data to provide information.

▪ It receives data as input, stores, manipulates and provides output in a useful format.
▪ Automatic: it carries out instructions with minimum human intervention
▪ Reprogrammable: it stores instruction (the program)
▪ A data processor: it carries out operations on data (numbers or words) made up of a
combination of digits to produce information.

3|
▪ Data is the name given to facts. Information is the meaningful data that is relevant,
accurate, up to date and can be used to make decisions.
▪ A computer accepts and then processes input data according to the instructions it is given.
▪ It is a machine capable of executing instructions to perform operations on data.
▪ The distinguishing feature of a computer is its ability to store its own instructions.
▪ This ability makes it possible for a computer to perform many operations without the need
for a person to enter new instructions each time.
▪ A Program is a set of coded instructions, which tells the computer what to do.
▪ For as long as the Instructions are being carried out, they are usually held in the computers’
internal storage or memory.

The set of instructions given to the computer to perform various operations is


called as the computer program. The process of converting the input data into the
required output form with the help of the computer program is called as data
processing. The computers are therefore also referred to as data processors
Therefore a computer can now be defined as a fast and accurate data
processing system that accepts data, performs various operations on the data, has the
capability to store the data and produce the results on the basis of detailed step by step
instructions given to it.

HISTORY OF COMPUTERS

Evolution of Computers

The computers of today are vastly different in appearance and performance as compared to the
computers of earlier days. But where did this technology come from and Where is it heading? To
fully understand the impact of computers on today’s world and the promises they hold for the
future, it is important to understand the evolution of computers.

The First Generation:


The first-generation computers made use of:
▪ Vacuum tube technology,
▪ Punched cards for data input,
▪ Punched cards and paper tape for output,
▪ Machine Language for writing programs,
▪ Magnetic tapes and drums for external storage.

4|
The computers of the first generation were very bulky and emitted large
amount of heat which required air conditioning. They were large in size and cumbersome
to handle. They had to be manually assembled and had limited commercial use. The
concept of operating systems was not known at that time. Each computer had a
different binary coded program called a machine language that told it how to operate.

The First Generation Computer technology

The Abacus, which emerged about 5000 years ago in Asia Minor and is still in use today, allows
users to make computations using a system of sliding beads arranged on a rack. Early merchants
used Abacus to keep trading transactions.

The first-Generation Computers

Blaise Pascal, a French mathematician invented the first mechanical machine, a rectangular brass
box, called Pascaline which could perform addition and subtraction on whole numbers. This was

5|
in the seventeenth century. Colmar, a Frenchman invented a machine that could perform the four
basic arithmetic functions of addition, subtraction, multiplication and division. Colmar’s
mechanical calculator, “Arithmometer”, presented a more practical approach to computing. With
its enhanced versatility, the “Arithmometer” was widely used until the First World War, although
later inventors refined Colmar’s calculator, together with fellow inventors, Pascal and Leibniz, he
helped define the age of mechanical computation. Charles Babbage a British mathematician at
Cambridge University invented the first analytical engine or difference engine. This machine
could be programmed by instructions coded on punch cards and had mechanical memory to
store the results. For his contributions in this field Charles Babbage is known as ‘the father of
modern digital computer’.

Some of the early computers included:

Mark I –

This was the first fully automatic calculating machine. It was designed by Howard Aiken of Harvard
University in collaboration with IBM. This machine was an electronic relay computer.
Electromagnetic signals were used for the movement of mechanical parts. Mark I could perform
the basic arithmetic and complex equations. Although this machine was extremely reliable, it was
very slow (it took about 3-5 seconds per calculation) and was complex in design and large in size.

Atanasoff-Berry Computer (ABC) –

This computer developed by John Atanasoff and Clifford Berry was the world’s
first general purpose electronic digital computer. It made use of vacuum tubes for internal
logic and capacitors for storage.

ENIAC (Electronic Numeric Integrator and Calculator) –

The first all-electronic computer was produced by a partnership between the US


Government and the University of Pennsylvania. It was built using 18,000 vacuum tubes,
70,000 resistors and 1,500 relays and consumed 160 kilowatts of electrical power. The
ENIAC computed at speed about thousand times faster than Mark I. However, it could
store and manipulate only a limited amount of data. Program modifications and
detecting errors were also difficult.

6|
ENIAC

EDVAC –

In the mid 1940’s Dr. John von Neumann designed the Electronic Discrete
Variable Automatic Computer with a memory to store both program and data. This was
the first machine which used the stored program concept. It had five distinct units -
arithmetic, central control, memory, input and output. The key element was the central
control. All the functions of the computer were co-ordinate through this single source, the
central control. The programming of the computers was done in machine language

UNIVAC • I –

Remington Rand designed this computer specifically for business data processing applications.
The Universal Automatic Computer was the first general purpose commercially available
computer.

7|
UNIVAC

The Second Generation:

In the Second Generation computers:

▪ Vacuum tube technology was replaced by transistorized technology,


▪ Size of the computers started reducing,
▪ Assembly language started being used in place of machine language,
▪ Concept of stored program emerged,
▪ High level languages were invented.

This was the generation of Transistorized Computers. Vacuum tubes were replaced by
transistors. As a result, the size of the machines started shrinking. These computers were smaller,
faster, more reliable and more energy efficient. The first transistorized computer was TX-0. The
first large scale machines that took advantage of the transistor technology were the early
supercomputers, Stretch by IBM and LARC by Sperry Rand. These machines were mainly
developed for atomic energy laboratories. Typical computers of the second generation were the
IBM 1400 and 7000 series, Honeywell 200 and General Electric.

8|
Transistors

IBM 1401 was universally accepted throughout the industry and largest businesses routinely
processed financial information using second generation computers. The machine language was
replaced by assembly language. Thus the long and difficult binary code was replaced with
abbreviated programming code which was relatively easy to understand.

The stored program concept and programming languages gave the computers flexibility to finally
be cost effective and productive for business use. The stored program concept implied that the
instructions to run a computer for a specific task were held inside the computer’s memory and
could quickly be modified or replaced by a different set of instructions for a different function.
High level languages like COBOL, FORTRAN and AL- GOL were dev eloped. Computers started
finding vast and varied applications. The entire software industry began with the second
generation
computers.

The Third Generation:

The Third Generation computers were characterized by:

▪ Use of Integrated circuits,


▪ Phenomenal increase in computation speed,
▪ Substantial reduction in size and power consumption of the machines,
▪ Use of magnetic tapes and drums for external storage,
▪ Design-of Operating systems and new higher level languages,
▪ Commercial production of computers.

This generation was characterized by the invention of Integrated Circuits (ICs). The 1C combined
electronic components onto a small chip which was made from quartz.

9|
i) Integrated Circuit ii) Integrated Circuit

Later, even more components were fitted onto a single chip, called a semiconductor. This
reduced the size even further. The weight and power consumption of computers decreased and
the speed increased tremendously. Heavy emphasis was given to the development of software.
Operating systems were designed which allowed the machine to run many different programs at
once. A central program monitored and co-ordinate the computer s memory. Multiprogramming
was made
possible, whereby the machine could perform several jobs at the same time. Computers achieved
speeds of executing millions of instructions per second. Commercial production became easier
and cheaper. Higher level languages like Pascal and Report Program Generator (RPG) were
introduced and applications oriented languages like FORTRAN, COBOL, and PL/1 were developed.

The Fourth Generation:

The general features of the Fourth Generation computers were:

▪ Use of Very Large Scale Integration,


▪ Invention of microcomputers,
▪ Introduction of Personal Computers,
▪ Networking,
▪ Fourth Generation Languages.

10 |
VLSI

The Third Generation computers made use of ‘Integrated Circuits that had 10- 20 components on
each chip, this was Small Scale Integration (SSI).

The Fourth Generation realized Large Scale Integration (LSI) which could fit hundreds of
components on one chip and Very Large Scale integration (VLSI) which squeezed thousands of
components on one chip. The Intel 4004 chip, located all the components of a computer (central
processing unit, memory, input and output controls) on a single chip and microcomputers were
introduced. Higher capacity storage media like magnetic disks were developed. Fourth generation
languages emerged and applications software’s started becoming popular.

Computer production became inexpensive and the era of Personal Computers (PCs) commenced.
In 1981, IBM introduced its personal computer for use in office, home and schools. In direct
competition, the Macintosh was introduced by Apple in 1984. Shared interactive systems and user
friendly environments were the features of these computers.

As the computers started becoming more and more powerful, they could be linked together or
networked to share not only data but also memory space and software. The networks could reach
enormous proportions with local area networks. A global web of computer circuitry, the Internet,
links the computers worldwide into a single network of information.

11 |
The Fifth Generation:

Defining the Fifth Generation computers is somewhat difficult because the field is still in its
infancy. The computers of tomorrow would be characterized by Artificial Intelligence (AI). An
example of AI is Expert Systems. Computers could be developed which could think and reason in
much the same way as humans. Computers would be able to accept spoken words as input (voice
recognition). Many advances in the science of computer design and technology are
coming together to enable the creation of fifth generation computers. Two such advances
are parallel processing where many CPUs work as one and advance in superconductor
technology which allows the flow of electricity with little or no resistance, greatly
improving the speed of information flow.

CLASSIFICATION OF COMPUTERS
Computers are broadly classified into two categories depending upon the logic used in their
design as:

Analog computers:

In analog computers, data is recognized as a continuous measurement of a physical property like


voltage, speed, pressure etc. Readings on a dial or graphs are obtained as the output, ex. Voltage,
temperature; pressure can be measured in this way.

Digital Computers:

These are high speed electronic devices. These devices are programmable. They process data by
way of mathematical calculations, comparison, sorting etc. They accept input and produce output
as discrete signals representing high (on) or low (off) voltage state of electricity. Numbers,
alphabets, symbols are all represented as a series of 1s and Os.

Digital Computers are further classified as General Purpose Digital Computers and Special Purpose
Digital Computers. General Purpose computers can be used for any applications like accounts,
payroll, data processing etc. Special purpose computers are used for a specific job like those used
in automobiles, microwaves etc.

Another classification of digital computers is done on the basis of their capacity to


access memory and size like:

12 |
Small Computers:

I) Microcomputers: Microcomputers are generally referred to as Personal Computers


(PCs). They have Smallest memory and less power. They are widely used in day to day
applications like office automation, and professional applications, ex. PCAT, Pentium etc.
II) Note Book and Laptop Computers: These are portable in nature and are
battery operated. Storage devices like CDs, floppies etc. and output devices like printers
can be connected to these computers. Notebook computers are smaller in physical
size than lap top computers. However, both have powerful processors, support
graphics, and can accept mouse driven input.

Small Computers

III) Hand Held Computers:


These types of computers are mainly used in applications like collection of field data. They are
even smaller than the note book computers.

1. Hybrid Computers: Hybrid Computers are a combination of Analog and Digital


computers. They combine the speed of analog computers and accuracy of digital
computers. They are mostly used in specialized applications where the input data is in an
analog form i.e. measurement. This is converted into digital form for further processing.

13 |
The computers accept data from sensors and produce output using conventional
input/output devices.
2. Mini Computers: Mini computers are more powerful than the microcomputers. They
have higher memory capacity and more storage capacity with higher speeds. These
computers are mainly used in process control systems. They are mainly used in
applications like payrolls, financial accounting, Computer aided design etc. ex. VAX, PDP-
11.
3. Mainframe Computers: Main frame computers are very large computers which process
data at very high speeds of the order of several million instructions per second. They can
be linked into a network with smaller computers, microcomputers and with each other.
They are typically used in large organizations, government departments etc. ex. IBM4381,
CDC.
4. Super Computers: A super computer is the fastest, most powerful and most expensive
computer which is used for complex tasks that require a lot of computational power. Super
computers have multiple processors which process multiple instructions at the same time.
This is known as parallel processing. These computers are widely used in very advanced
applications like weather forecasting, processing geological data etc. ex. CRAY-2, NEC -
500, PARAM.

14 |
MODULE TWO

REVIEW OF BASIC CONCEPTS OF COMPUTER COMPONENTS

Introduction to Computer

This lecture focuses on basic definitions of computer, history of computer, generations of


computer, classification of computer, basic elements of computer system.

COMPONENTS OF COMPUTER SYSTEM


There are two components of computer system: Hardware and Software components

Hardware
Physical equipment/components that make up a computer system that we can actually touch e.g.
I/O devices, processors, cables & circuits.

• It consists of several interconnected devices or components.

Examples of Hardware component of a Computer System

15 |
Central Processing Unit (CPU) Or Processor

• The CPU is an electronic circuit that can execute computer programs

• CPU performs most of the calculation which enable computer to function, and it is sometimes
referred to as the brain of the computer.

• The more powerful the processor, the faster the system goes.

• The CPU is divided into two parts;

Arithmetic/Logic Unit (ALU

processes data arithmetically (addition, subtraction, multiplication, division) or logically (greater


than, less than, equal to).

• Control Unit: works with the operating system to move data between auxiliary storage and main
memory; and between main memory and the ALU

Memory

▪ This is the internal storage areas in the computer.


▪ The term memory identifies data storage that comes in the form of chips i.e. RAM
▪ The word storage is used for memory that exists on tapes or disks i.e. Hard drive.

RAM

• Stands for Random access memory


• Its purpose is to store the information and instructions that operate the computer's programs
• A more recent development is the solid-state RAM.
• Solid state RAM can contain information even if there is no power supply.
• Flash drives are removable storage devices that utilize solid-state RAM to store information for
long periods of time.
There are mainly two types of RAM
• Dynamic RAM (DRAM) and
• Static RAM (SRAM).

16 |
Software Component

Software: set of instructions that causes the hardware to function in a desired way. A collection of
lines of instruction is called a program.

Types of software

This consists of 1) System Software 2) Application Software

System Software

• It is the interface between the user and hardware.


• Better still, it is the interface between application software and hardware.
• System software can be classified into three:
• Operating system,
• Translators and
• Utility program

OPERATING SYSTEM (OS)

• It is the software that manages the resources of a computer system and schedules its operations.
• It acts as the interface between the hardware and other user programs and facilitates the
execution of programs.

• UNIX

• MS-DOS

• Windows

TRANSLATORS

• Computers can understand instructions only when they are written in their own
language, “the machine language”.

17 |
• Therefore, a program written in any other language should be translated into machine language.
• The software that “translates” the instructions of

• different languages are known as translators.

There are two types of translators; 1) Compilers 2) Interpreters

1. Compilers: A compiler is a software program that transforms high-level source code that is
written by a developer in a high-level programming language into a low-level object code
(binary code) in machine language, which can be understood by the processor. The process
of converting high-level programming into machine language is known as compilation.

2. Interpreters: An interpreter is a computer program that is used to directly execute program


instructions written using one of the many high-level programming languages. It can also be
defined as a computer language processor that translates a program line-by-line (statement-
by-statement) and carries out the specified actions in sequence. In contrast, an assembler or
compiler completely translates a program written in a high-level language (the source
program) into a machine-language program (the object program) for later execution. Whereas
a compiled-program executes much faster than an interpreted-program, an interpreter allows
examination and modification of the program while it is running (executing).

APPLICATIONS OF COMPUTERS
Today computers find widespread applications in all activities of the modern world. Some of the
major application areas include:

Scientific, Engineering and Research:

This is the major area where computers find vast applications. They are used in areas which require
lot of experiments, mathematical calculations, weather forecasting, and complex mathematical
and engineering applications. Computer Aided Design (CAD) and Computer Aided Manufacturing
(CAM) help in designing robotics, automobile manufacturing, automatic process control devices
etc.

Business:
Record keeping, budgets, reports, inventory, payroll, invoicing, accounts are all the areas of
business and industry where computers are used to a great extent. Database management is one
of the major area where computers are used on a large scale. The areas of application here include
banking, airline reservations, etc. where large amounts of data need to be updated, edited, sorted,
searched from large databases.

18 |
Medicine:
Computerized systems are now in widespread use in monitoring patient data like , pulse rate,
blood pressure etc. resulting in faster and accurate diagnosis. Modern day medical equipments
are highly computerized today. Computers are also widely used in medical research.

Information:
This is the age of information. Television, Satellite communication, Internet, networks are all based
on computers.

Education:
The use of computers in education is increasing day by day. The students develop the habit of
thinking more logically and are able to formulate problem solving techniques. CDs on a variety of
subjects are available to impart education. On line training programs for students are also
becoming popular day by day. All the major encyclopedias, dictionaries and books are now
available in the digital form and therefore are easily accessible to the student of today. Creativity
in drawing, painting, designing, decoration, music etc. can be well developed with computers.

Games and Entertainment:

Computer games are popular with children and adults alike. Computers are nowadays also used
in entertainment areas like movies, sports, advertising etc.

ADVANTAGES AND DISADVANTAGES OF COMPUTERS


Advantages of Computers:

1. Speed:
The speed of a computer is measured in terms of the number of instructions that it can
perform or execute in a second. The speeds of computers are measured in milliseconds (10~3
sec), micro-seconds (10*6 sec), and nano-seconds (10~9sec). Computers are superfast
machines and can process millions of instructions per second. Smaller computers can execute
thousands of instructions per second, while the more complex machines can execute millions
of instructions per second.
2. Accuracy:
Computers are very accurate. They are capable of executing hundreds of instructions without
any errors. They do not make mistakes in their computations. They perform each and every
calculation with the same accuracy.
3. Efficiency
The efficiency of computers does not decrease with age. The computers can perform repeated

19 |
tasks with the same efficiency any number of times without exhausting their selves. Even if
they are instructed to execute millions of instructions, they are capable of executing them all
with the same speed and efficiency without exhaustion.
4. Storage Capability
Computers are capable of storing large amounts of data in their storage devices. These dev
ices occupy very less space and can store millions of characters in condensed forms. These
storage devices typically include floppy disks, tapes, hard disks, CDs etc, the data stored on
these devices can be retrieved and reused whenever it is required in future.
5. Versatility
Computers are very versatile. They are capable not only of performing complex mathematical
tasks of science and engineering, but also other non-numerical operations fielding air-line
reservation, electricity bills, data base management etc.

Limitations of Computers:

Although the computers of today are highly intelligent and sophisticated, they have their own
limitations. The computer cannot think on its own, since it does not have its own brain. It can only
do what is has been programmed to do. It can execute only those jobs that can be expressed as
a finite set of instructions to achieve a specific goal. Each of the steps has to be clearly defined.
The computers do not learn from previous experience nor can they arrive at a conclusion without
going through all the intermediate steps. However, the impact of computers on today’s society in
phenomenal and they are today an important part of the society.

SIMILARITIES AND DIFFERENCE BETWEEN HUMAN AND COMPUTER


Computer is a very effective and efficient machine which performs several activities in few minutes,
which otherwise would have taken several days if performed naturally. Besides there would have
been a doubt about the accuracy, finish etc. The computer may be faster; more accurate but it
cannot compete with human brain. However, there are some similarities between the human and
the computer which would make the computer more understandable.

Human Computer

# Like human beings has ears, nose, eyes etc. Computers have input devices such as
keyboard, scanner, touch screen, mouse etc to
get information.

20 |
# Like we remember things Computer also stores information

#We recollect certain information as required. The computer also retrieves information when
times,

#We express ourselves by speech, writing etc Computer expresses through screen, Printouts
etc which We call as output.

#When we watch, hear, learn certain things with the help of software, computer
and analyze. also can analyze Information and draw
conclusions.

#The place where we store, analyze, The computer brain is known as CPU conclude
information is known as the brain (Central
Processing Unit) where it analyses information.

The computer has storage devices like floppies, hard disks, compact disks to store and retrieve
information.

However, computer does not understand emotions, it does not understand meaning beyond
words, it cannot read between the lines like the human. We learn many things unknowingly,
certain things knowingly; we call it as upbringing. But computers can learn everything only
knowingly. We learn many things on our own, but computer has to be taught to do everything.

21 |
MODULE THREE

PROBLEM SOLVING USING ALGORITHM, FLOWCHART AND PSEUDOCODE

The primary reason of using computer is make our work faster. We program computer to work in
accordance to our need. For instance, registration of our courses and checking balance of our
money using our phones. These are applications given to the computer to act in such ways when
asked to perform such tasks.

Programmers use computer programs to write the instructions to the computer to obey and
perform such tasks. The act of writing such instructions for computer is called programming. But
the computer cannot understand human language like Hausa, Yoruba, Igbo or English. Rather, the
computer has its own languages that is close to human language. These languages are called
programming languages. The programmer has to learn the computer language in order to write
the instructions for the computer to execute and produce the desired result.

Computer instructions to execute can be as simple as telling the computer to accept name of a
student or a customer and display the name on a computer screen or it can be a complex one like
taking in list of students and individual student scores for all courses from year 1 to year 4 and
compute GP, CGPA and the status and class of degree.

Writing such instructions/program for computer to execute can be confusing and hair scratching.
To simplify this process, programmers came up with a process called problem solving techniques.
This process is to be done before writing the computer program. The problem must be identified
and offer a solution using a tool for problem-solving technique. Writing the program will be
discuss in module four.

Algorithms, flowcharts and pseudocode are different tools used for creating a solution prior to
writing a computer new program. An algorithm is a step-by-step analysis of the process, while a
flowchart explains the steps of a program in a graphical way. Pseudocode is a form of algorithm
written in human language-like, e.g. English, Hausa, Kanuri etc.

ALGORITHM
An algorithm is just a detailed sequence of simple steps that are needed to solve a problem. To
write a logical step-by-step method to solve the problem is called algorithm, in other words, an
algorithm is a procedure for solving problems. In order to solve a mathematical or computer
problem, this is the first step of the procedure. An algorithm includes calculations, reasoning and

22 |
data processing. Algorithms can be presented by natural languages, pseudo code and flowcharts,
etc.

An algorithm may be expressed in a number of ways, including:

1. natural language: usually verbose and ambiguous. We write in our own thoughts.
2. flow charts: avoids most (if not all) issues of ambiguity; difficult to modify w/o specialized
tools; largely standardized.
3. pseudocode: also avoids most issues of ambiguity; vaguely resembles common elements of
programming languages; no particular agreement on syntax
4. programming language: tend to require expressing low-level details that are not necessary
for a high-level understanding.

An algorithm must possess the following properties

1. Finiteness: The algorithm must always terminate after a finite number of steps.
2. Definiteness: Each step must be precisely defined; the actions to be carried out must be
rigorously and unambiguously specified for each case.
3. Input: An algorithm has zero or more inputs, taken from a specified set of objects.
4. Output: An algorithm has one or more outputs, which have a specified relation to the
inputs.
5. Effectiveness: All operations to be performed must be sufficiently basic that they can be
done exactly and in finite length.

Algorithmic solution

23 |
Characteristics of an Algorithm
Well-ordered: the steps are in a clear order
Unambiguous: the operations described are understood by a computing agent without
further simplification
Effectively computable: the computing agent can actually carry out the operation

Method for Developing an Algorithm


1. Define the problem: State the problem you are trying to solve in clear and concise
terms.
2. List the inputs (information needed to solve the problem) and the outputs (what the
algorithm will produce as a result)
3. Describe the steps needed to convert or manipulate the inputs to produce the
outputs.
Start at a high level first, and keep refining the steps until they are effectively computable
operations.
4. Test the algorithm: choose data sets and verify that your algorithm works.

Algorithm example

Example 1:

Assuming that the gross pay of an employee is to be calculated and then 10 percent of
the gross is to be deducted as tax while the remaining gives the net pay. Write down the
algorithm for this problem.

Solution:

Begin
input name, hours-worked, and wage/hour
Calculate gross-pay = hours-worked * wage/hour
Calculate tax = (10/100) * gross-pay
Calculate net-pay = gross-pay – tax
Print name, net-pay
End

Example 2:

24 |
Write an algorithm to read the name and the mark of one student and then add 5 to
his/her mark.

Solution
Begin
input name, mark
New-mark = mark + 5
print name, new-mark
End

FLOWCHART
A flowchart is the graphical or pictorial representation of an algorithm with the help of different
symbols, shapes and arrows in order to demonstrate a process or a program. With algorithms,
we can easily understand a program. The main purpose of a flowchart is to analyze different
processes. Several standard graphics are applied in a flowchart:

General Rules for Flowcharts


1. All symbols of the flowchart are connected by flow lines (note arrows, not lines)
2. Flow lines enter the top of the symbol and exit out the bottom, except for the Decision
symbol, which can have flow lines exiting from the bottom or the sides
3. Flowcharts are drawn such that flow generally goes from top to bottom
4. The beginning and the end of the flowchart is indicated using the Terminal symbol

25 |
Draw the flowchart for these algorithms

Algorithm Flowchart

Begin
input name, mark
new-mark = mark + 5
print name, new-mark
End

Begin
input base, height
area = 0.5*base*height
print area
End

26 |
PSEUDOCODE
Pseudocode is writing an algorithm in any natural language, like English. It models and resembles
real programming code, and is written at roughly the same level of detail, but is not specifically in
any programming language. The advantage is it can then be translated into any programming
language.

Pseudocode consists of short, English phrases used to explain specific tasks within a program.
Ideally, pseudocode should not include keywords in any specific computer language. Pseudocode
should be written as a list of consecutive phrases; we can even draw arrows to show looping
processes. Indentation can be used to show the logical program flow in pseudocode.

Writing pseudocode saves time later during the coding and testing stage of a program’s
development and also helps communication among designers, coders and project managers.
Some projects may use pseudocode for design, others may use flowcharts, and some a
combination of both.

A statement is defined as an instruction that directs the computer to perform a specific action. In
writing pseudocode, we will refer to singular instructions as statements.

When writing pseudocode, we assume that the order of execution of the statements is from top
to bottom. This changes when using control structures, functions and exception handling.
Examples of statement are:

Area = 0.5*base*height

Force = mass*acceleration

Amount_of_soil < amount_of_ammonia

Pseudocode uses mathematical operators like:

Assignment: ← or :=

Example: c ← 2πr, c := 2πr

Comparison: =, ≠, <, >, ≤, ≥

Arithmetic: +, −, ×, /, mod

Logical: and, or

Pseudocode also uses keywords

27 |
A keyword is a word that is reserved by a program because the word has a special meaning.
Keywords can be commands or parameters. Every programming language has its own keywords
(reserved words). In Pseudocode, they are used to indicate common input-output and
processing operations. They are written fully in uppercase. Keywords cannot be used as
variable names. Examples are:

START: This is the start of your pseudocode.

INPUT: This is data retrieved from the user through typing or through an input device.

READ / GET: This is input used when reading data from a data file.

PRINT, DISPLAY, SHOW: This will show your output to a screen or the relevant output device.

COMPUTE, CALCULATE, DETERMINE: This is used to calculate the result of an expression.

SET, INIT: To initialize values

INCREMENT, BUMP: To increase the value of a variable

DECREMENT: To reduce the value of a variable

During algorithm development, we need statements which evaluate expressions and execute
instructions depending on whether the expression evaluated to True or False. Here are some
common conditions used in Pseudocode:

IF … THEN IF you are happy


THEN smile
ENDIF
ELSE…IF IF you are happy THEN
smile
ELSE IF you are sad
frown
ELSE
keep face plain
ENDIF
DO… WHILE DO
count = count+1
WHILE
count < 20
WHILE … DO WHILE count < 20
count = count+1
DO

28 |
FOR… NEXT FOR
Student_no= 1 to 20
PRINT student_no
NEXT student_no

Let's see an example of a pseudocode to create a program to add 2 numbers together and then
display the result.

Start Program
Enter two numbers, A, B
Add the numbers together
Print Sum
End Program

Now, let's look at a few more simple examples of pseudocode. Here is a pseudocode to
compute the area of a rectangle:

Get the length, l, and width, w


Compute the area = l*w
Display the area

Now, let's look at an example of pseudocode to compute the perimeter of a rectangle:

Enter length, l
Enter width, w
Compute Perimeter = 2*l + 2*w
Display Perimeter of a rectangle

Final note on pseudocode: There are no technical rules for Pseudocode. It is meant to be
human readable and still convey meaning and flow. Sultan can write pseudocode different from
Abba Aji. But the important thing is the final result when implemented as a program.

29 |
EXAMPLES OF FLOWCHARTS FOR ALGORITHMS

These examples will help you get a better understanding of flowchart techniques.

Example 1: Calculate the Interest of a Bank Deposit

Algorithm:

• Step 1: input amount,


• Step 2: input years,
• Step 3: input rate,
• Step 4: Calculate the interest with formula "Interest=Amount*Years*Rate/100
• Step 5: Print interest,

Flowchart:

Example 2: Determine and Output Whether Number N is Even or Odd

Algorithm:

• Step 1: input number N,

30 |
• Step 2: Set remainder as N modulo 2,
• Step 3: If remainder is equal to 0 then number N is even, else number N is odd,
• Step 4: Print output.

Flowchart:

Example 3: Determine Whether a Temperature is Below or Above the Freezing Point

Algorithm:

• Step 1: Input temperature,


• Step 2: If it is less than 32, then print "below freezing point", otherwise print "above
freezing point"

31 |
Flowchart:

Example 4: Determine Whether A Student Passed the Exam or Not:

Algorithm:

• Step 1: Input grades of 4 courses M1, M2, M3 and M4,


• Step 2: Calculate the average grade with formula "Grade=(M1+M2+M3+M4)/4"
• Step 3: If the average grade is less than 60, print "FAIL", else print "PASS".

32 |
Flowchart:

33 |
MODULE FOUR

INTRODUCTION QBASIC PROGRAMMING


In the early days of programming, it was usually the scientific elite doing the programming and
they were usually trained above and beyond the average individuals to do their programming
work. Until 1964 at Dartsmouth college when the Beginner's All-purpose Symbolic Instruction
Code was introduced -- known as BASIC. Using common English to perform processor tasks,
BASIC became quickly popular, although it was disliked by programmers of more "low-level"
languages such as assembly and FORTRAN. In 1985 Microsoft released their own version of BASIC
called QBasic with their MS-DOS 5.0 operating system. Since then, nearly every PC user owns their
own copy of QBasic, making it a widely known language. QBasic is a very simple language to pick
up, and yet it can accomplish a great deal. Granted you will probably never write Doom or Word
Perfect with QBasic, but it has its strong points. One of them is to introduce people to
programming without having to worry about the internal workings of the computer. It's simple to
create games, business applications, simple databases, and graphics. The best aspect of the
language is its close resemblance to English.

Once you got the problem solved using the problem technique, the problem can be written using
the QBASIC. You use the QBASIC syntax and statements to write and execute the program. This
course is about programming, but do not try to make you a programmer. The goal is to increase
your understanding of computers in the modern world. But if you are thinking about becoming a
programmer, studying this course is a good first step. However, the course aimed at students who
are not computer science majors for the fact that details have been kept to a minimum.

Facts about Computer Languages:

1. All computer programming languages are fundamentally the same.

o All programmers have the same fundamental understanding of programming,


regardless of what particular programming language they use.

2. Any program can be written with any programming language.

o However, some languages are more effective for some types of programs.

Small Programs

In this module you will learn to write small programs in the QBasic computer programming
language.

34 |
QBASIC OPERATORS, VARIABLES, EXPRESSIONS AND STATEMENTS

Arithmetic Operators

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

Relational Operators

Operator Meaning Example


< less than 2<3
> greater than 5>2
<= less than or equal to 2<=3
>= greater than or equal to 2>=2
= equal to 2=2
<> not equal to 3 <> 2

35 |
Logical Operators

Opetrator Meaning Example


AND Logical AND 2 AND 5
OR Logical OR 4 OR 6
NOT Logical NOT State NOT Yobe

DATA TYPES / VARIABLES

Variables: Are extremely important to understand. A variable is a value associated with a


storage location in memory of a computer whose value can change during program execution;
the memory location remains the same, but the variable's value may change. Variables allow the
programmer to manipulate data however many times he needs to during program execution.
Programmers give names to memory storage locations called variable names so they can use
them in programs. It is important to note that when you name variables, you should use
descriptive names so you and others will be able to understand and read the program code
easily. The name of the variables should reflect the value of what the variable holds or will hold.

Data Types: There are two types of variables in QBasic: numeric and string. A numeric variable
can further be broken down into three categories: integer, single precision, or double precision
and is capable of storing numeric values. A string variable is capable of storing character string
values.

A numeric variable name must begin with a letter, followed by letters, digits, and periods (no
blanks or underscores). By default, a variable will automatically be thought to be of single
precision type, which is capable of accurately displaying numbers up to seven decimal places.
You can specify a variable to be of single precision type by using the following syntax:

data
data!

Notice that an exclamation point ( ! ) is attached to the end of the second variable name. This is
not needed but is often used in programs so the programmer will know that data is of single
presicion type. A double precision type is used when the programmer is working with large
values that may need to display numbers up to fifteen decimal places. You can specify a variable
to be of doulbe precision type by using the following syntax:

36 |
data#

Notice the pound symbol ( # ) attached to the end of the variable. This lets QBasic associate
data as being of double precision type. There may be times when you are strictly working with
integer values and have no need to use floating point values (single or double types). In this
case, you can specify the variable to be of type integer. You can specify a variable to be of
integer type by using the following syntax:

data%

Notice the percentage symbol ( % ) attached to the end of the variable. This lets QBasic
associate data as being of integer type. If working with extremely large integral values, you can
specify the variable to be of type long by using the following syntax:

data&

Notice the ambersand symbol ( & ) attached to the end of the variable. This lets QBasic
associate data as being of long integer type.

Some valid an invalid numeric variable names are provided below:

Valid Numeric Variable Names


firstTest
profit&
gpa!
total.Price
company8
COURSE2D

Invalid Numeric Variable Names


1stClass --> (must begin with letter)
total Price --> (no spaces)
name,First --> (no commas)

A string variable name must begin with a letter, followed by letters and digits, and must be
terminated with a dollar sign ($). The dollar sign simply alerts the compiler that the variable is a
string variable. Some valid and invalid string variable names are provided below:

Valid String Variable Names


firstName$

37 |
heading$
course23Name$

Invalid String Variable Names


firstName --> (must end with $)
company Name$ --> (no spaces)
name,First$ --> (no commas)

Dimensioning Variables
QBasic allows programmers to dimension or declare a variable by using the DIM statement. If
you choose to dimension variables in this way, the DIM statement(s) must be placed at the very
beginning of your program before the variable(s) are used in the program. After you declare a
string variable using the DIM statement, you do not need to attach the dollar sign ( $ ) to the
end of the string variable thereafter in the program and QBasic will actually generate an error if
you try to. The DIM statement is used to declare variables as follows:

DIM state AS STRING

DIM number AS INTEGER

DIM profit AS DOUBLE

DIM gpa AS SINGLE

When declaring string variables, you can also take advantage of specifing fixed lengths or a
maximum amount of characters for the string variables. If declared as being with a fixed length,
the variable will always contain that specifed length in all situations. If you try to place less
characters into the string than the max size, spaces will be provided for the trailing characters. If
you try to place more characters into the string than the max size, the extra character values will
be truncated off. Fixed length declarations can be done as follows:

DIM name AS STRING * 25

QBasic programs also contain many keywords, which are pre-defined in QBasic and have special
meaning. Some keywords include READ, LIST, PRINT, and END, which I describe later. Because
keywords are pre-defined and have special meaning, you cannot use them as variable names.

Simple QBasic Statements


The following statements are extremely simple to learn, and you will probably use them in most
of your programs.

38 |
CLS - simply clears the output screen and positions the active cursor to the upper left corner of
screen (0,0). You should almost always place CLS at the very beginning of your program code so
you will not see any output produced from previous programs when you execute your current
program.

REM - used for documentation purposes. Documentation is very important in programming and
you should get into the habit of documenting your code. Documentation statements are not
executed by the program and do not affect the program code. They simply tell the programmer
or other programmers viewing the code what particular segments of the code are supposed to
do. You should also place appropriate documentation at the beginning of your code explaining
the purpose of the program, the date last updated, your name as the programmer who wrote it,
and any other information that may be appropriate for the program.

' (single quotation mark) - also used for documentation purposes

LET - implies an assignment statement, which are statements used to assign a value to a
variable. For example, consider:

LET total = 90 --> assigns value of 90 to total


LET name$ = "your name" --> assigns value of your name to name$

NOTE: LET is optional and does not need to be included in the program code. For example, the
above statements could also be written as:

total = 90 --> assings value of 90 to total


name$ = "your name" --> assigns value of your name to name$

For simplicity sake, I will not include LET during assignment statements throughout the rest of
this tutorial.

Obviously, if we are going to talk about assignment statements and variables, we will need to
know the type of arithmetic operators that are compatible with QBasic. The basic arithmetic
operators are as follows:

+ : addition
- : subtraction
/ : division
* : multiplication
^ - exponentiation

39 |
The operator precedence (order of operations) is as follows:

1 - Exponentiation
2 - Multiplication, Division
3 - Addition, Subtraction
4 - same level ops. are preformed from left-to-right

For example, consider the following statements:

A = B ^ 3 --> B is cubed and the result is stored in A


A = 2 * 7 + 10 --> A is assigned 24

NOTE: You must use parentheses if you want to force the compiler to evaluate particular
expressions in a statement before others. For example,

X = (A + B) * C --> A is added to B and then that result is multiplied by C and stored in X

Ok, so we know about variables and operators, but how do we actually display results to the
output screen. We use PRINT to output information to the output screen. I explain further in
detail about the PRINT statement and output in the next section.

PRINT - prints literals, values of variables, and arithmetic expressions to output screen

You can use commas to format a PRINT statement which insert a tab space across the output
line. For example,

PRINT "NAME", "TEST", "SCORE"

would output something like:

NAME TEST SCORE

When using the PRINT statement, all character values must be enclosed with double quotation
marks, but numeric literals do not need to be enclosed with double quotation marks. Also,
issuing PRINT, alone, prints a blank line on the screen (skipping a line by leaving it blank).

END is a statement that should be placed at the end of every program you write. END instructs
the compiler to terminate program execution.

40 |
The following is a program with basic statements (which are described above) that you can save
and use as a default setup program for when you start to write a new program:

REM PURPOSE:

REM

REM

REM PROGRAMMER:

REM DATE LAST UPDATED:

CLS

END

Now let’s start the program tutorial with appropriate examples

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:

The picture shows many details that are not important right now. The QBasic program is just these
two lines:

PRINT 10 + 5

41 |
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

How many statements are in this program?

Answer:

Two.

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.

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

42 |
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 usual multiply symbol (which is not
on the computer keyboard). The character * is on the same key as "8" on the computer keyboard.

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.

STRINGS AND ARITHMETIC IN PRINT STATEMENTS

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

43 |
' Printing two items

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

END

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

44 |
QBasic did not execute the PRINT statement on Q.11 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."

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.

Bugs

The program should be:

' Computing 12 times 12

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

END

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

45 |
The buggy program:

' Computing 12 times 12

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

END

. . . 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

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

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 program that calculates the number of miles per gallon for a car that has burned 10
gallons of gas and gone 245.4 miles:

46 |
QUESTION 16:

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

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.

ARITHMETIC EXPRESSIONS

This chapter is about arithmetic with QBasic. The rules for QBasic arithmetic are similar to paper-
and-pencil arithmetic.

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.

47 |
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

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

1+2*3

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

48 |
- 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

Do this:

2*3+1

Answer:

2*3+1 = 6+1 = 7

--+--

higher priority

than +,

do first

QUESTION

What is the result of the following?

10 + 3 * 3 + 5

49 |
Answer:

The highest priority operator in

10 + 3 * 3 + 5

is *, so it is done first. This gives

10 + 9 + 5.

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

10 + 9 + 5 = 19 + 5 = 24

Equal Priority for * and /

Examine the priority chart again: Notice that * and / have the same priority. When there are several
* 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

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

+ 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

What is the result of the following?

50 |
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

* 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.

QUESTION

What operator is done next?

8+3-8/2

Answer:

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

Exponents

In the priority chart, exponent is the highest priority of all. This means that it will be done before
anything else. Remember that "^" means "raised to the power of".

QUESTION 11:

What operator will be done first in the following?

51 |
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

-----

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

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.

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

The LET Statement

Look at the (first) program again:

' Program that uses a variable

52 |
'

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

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

53 |
END

Answer:

The program will print:

The result is 5

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

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.

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

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

54 |
' 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.

' 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:

55 |
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

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

Answer:

The program will print:

Hours per Week 12

Hours per Semester 180

56 |
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.)

57 |
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:

' Attempt to use two versions of the same name

'

LET VALUE = 123

58 |
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

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

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

59 |
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

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)

• Since the 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

60 |
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.

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:

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.)

61 |
3. Replaces the contents of the variable to the left of the equal sign with the result of the
calculation.

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

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

THE INPUT STATEMENT

The INPUT statement gets data from the computer keyboard. Commonly, the user of the
program provides this data and thus has some control over the program’s behavior.

In True BASIC, the simplest way to obtain data from the user is the INPUT statement. The data
provided by the user may consist of numeric or string values, and it may come from the
keyboard or a file.

The INPUT statement pauses the program, prints a question mark (?) at the current text cursor
position, and then displays the text cursor (if it is turned on). A visible text cursor indicates that
the user must enter data before the program will continue.

The number and type of variables specified as input items determine the number and type of
values the user must supply. The program may include as many input items as necessary in an
INPUT statement, separating them with commas. Consider the following example lines:
INPUT a
INPUT x, y
INPUT name$, age, phone$

62 |
PROGRAM EXAMPLES

63 |
End of the course

64 |

You might also like