MTH 208-Intro To Comp Programming
MTH 208-Intro To Comp Programming
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
Introduction to Computer
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.
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.
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 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.
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’.
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.
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.
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
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.
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.
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:
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.
12 |
Small Computers:
Small Computers
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
Introduction to Computer
Hardware
Physical equipment/components that make up a computer system that we can actually touch e.g.
I/O devices, processors, cables & circuits.
15 |
Central Processing Unit (CPU) Or Processor
• 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.
• Control Unit: works with the operating system to move data between auxiliary storage and main
memory; and between main memory and the ALU
Memory
RAM
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
System Software
• 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
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.
APPLICATIONS OF COMPUTERS
Today computers find widespread applications in all activities of the modern world. Some of the
major application areas include:
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.
Computer games are popular with children and adults alike. Computers are nowadays also used
in entertainment areas like movies, sports, advertising etc.
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.
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
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.
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.
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
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:
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
Assignment: ← or :=
Arithmetic: +, −, ×, /, mod
Logical: and, or
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:
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.
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:
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:
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.
Algorithm:
Flowchart:
Algorithm:
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:
Algorithm:
31 |
Flowchart:
Algorithm:
32 |
Flowchart:
33 |
MODULE FOUR
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.
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
/ divide 12 / 4 12 divided by 4
- subtraction 9 - 2 9 minus 2
Relational Operators
35 |
Logical Operators
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.
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:
37 |
heading$
course23Name$
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:
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:
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.
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.
LET - implies an assignment statement, which are statements used to assign a value to a
variable. For example, consider:
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:
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
NOTE: You must use parentheses if you want to force the compiler to evaluate particular
expressions in a statement before others. For example,
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,
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:
CLS
END
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
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:
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.
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:
42 |
PRINT 1.5 + 4.2
END
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:
PRINT 12.1 * 2
END
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:
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.
A PRINT statement can print more than one item. Examine the following program.
43 |
' Printing two items
END
The two items are separated by a comma ( , ). When the program runs it prints the following to
the monitor:
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?
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.
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:
END
Answer:
Yes. The string in the PRINT statement does not have quotes around it.
Bugs
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:
END
Answer:
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:
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:
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:
END
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:
' 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
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:
-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
1+2*3
1+2*3 ?
Answer:
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".
^ power 1
48 |
- negation 2
* multiply 3
/ divide 3
+ addition 4
- subtraction 4
For example:
1+2*3
= 1 + 6
= 7
QUESTION
Do this:
2*3+1
Answer:
2*3+1 = 6+1 = 7
--+--
higher priority
than +,
do first
QUESTION
10 + 3 * 3 + 5
49 |
Answer:
10 + 3 * 3 + 5
10 + 9 + 5.
Now the remaining + are of equal priority and are done left to right.
10 + 9 + 5 = 19 + 5 = 24
Examine the priority chart again: Notice that * and / have the same priority. When there are several
* and /, do them left to right. For example:
4*2
The / and * have equal priority. The operators are done left to right.
QUESTION
10 * 2 / 4
Answer:
10 * 2 / 4
10 * 2 / 4 = 20 / 4 = 5
Notice that + and - also have equal priority. If they are the only operators in an expression, do
the work from left to right.
QUESTION
50 |
12 - 2 + 4
Answer:
12 - 2 + 4
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:
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
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:
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
-----
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:
'
END
When this program runs, the value 23.5 is placed in the variable NUM. Then the following is
written to the monitor:
52 |
'
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:
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:
The variable NUM already exists, so no more memory is reserved for it. The PRINT statement
does several things:
QUESTION
What do you think the following program will write to the monitor?
'
LET VALUE = 2 + 3
53 |
END
Answer:
The result is 5
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.
'
LET AGE = 23
PRINT "You have lived more than", AGE * 365, " days"
END
Answer:
Calculation
3. It multiplies that value by 365 but DOES NOT change the contents of AGE .
QUESTION
What do you think the following program will write to the monitor?
54 |
' Pounds to ounces
'
LET POUNDS = 3
END
Answer:
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.
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.
'
LET MILE = 5
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 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?
'
LET CLASSES = 4
END
Answer:
56 |
Ho Hum...
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.)
1. A variable is a small amount of computer memory that has been given a name.
o up to 40 characters long,
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:
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?
MyValue 16Candles
SUM23 YEAR%
Answer:
If two names differ only in upper and lower case characters, they are really the same name.
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:
'
58 |
PRINT value
As soon as you move the cursor out of the PRINT statement the QBasic system will change your
program:
'
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?
Answer:
'
LET DAYS = 3
END
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:
'
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)
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:
Answer:
No. Memory is found for a variable the first time it is used in a statement.
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.
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.
The contents of a variable can be replaced many times. Examine the following program:
'
LET VALUE = 1
PRINT VALUE
LET VALUE = 2
PRINT VALUE
LET VALUE = 3
PRINT VALUE
END
QUESTION 23:
Answer:
A LET statement can do quite a bit of work. You have seen examples of this already. Consider
this statement:
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
'
LET A = 2
LET B = 4
LET C = (A + B) / 2
PRINT A, B, C
END
Answer:
2 4 3
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 |