# Programming

Document Sample

```					Picnic Point High School
Computing Studies
Year 10

Programming
Student Booklet

Programming          1
Picnic Point High School
Programming
Introduction
Computers are tools that we use to solve problems. Some problems might be able to be
solved by using programs written by someone else.

These notes were written with the help of a program called a word processor. A team of
people at Microsoft wrote a program called WORD, which solves the problem of producing
neat, written documents. MYOB is a program, written by a team of people, to solve the
problem of keeping track of a business’s finances. Computer games are written by people to
solve the problem of entertaining the players.

Other problems might be too small, or too specific to one
person/business type, so that there is no market to make it
profitable for a professional programmer to write a program as a
solution. In these cases the user needs to write their own
program. This unit is devoted to teaching you how to program
computers to do what you want.

Problem Solving
Since a program is the solution to somebody’s problem, before you can write the program
you need to be able to solve the problem. This usually isn’t as difficult as it sounds.

There are three main steps involved in producing the solution to a problem. They are:
 Define the problem – you can’t solve a problem you don’t understand. You should find
out:
o The Outputs – what does the user want the program to produce?
o The Inputs – what information is needed to produce those outputs?
o The Processes – how are the inputs turned into outputs?
 Write the solution as an algorithm – an algorithm is like a recipe: it lists the steps
involved in accomplishing a task. Each step must be short enough so that it can be easily
carried out and must be performed in a particular order (sequence). The usual order is
Input, Process, Output.
 Check the algorithm – This step is the most important but is the step most often
forgotten. A desk check is used by the programmer to make sure the algorithm is correct.
A correct algorithm can be turned into a program that works. Problem solved!

Now that you can describe the steps that have to be performed in the correct sequence to
accomplish the task, all that is left to do now is:
 Code the algorithm in a programming language – like BASIC, Pascal or C++
 Check the program – to check that there are no syntax errors, typing errors or steps
from the algorithm accidentally omitted (left out).
 Document the program – documenting your program is really done right throughout the
program development, from the time you list the outputs to when you deliver the final
program. Documenting the program helps other programmers to understand how it works
and makes it easier to maintain the program (modify it to meet changed demands from
the users).

The six steps above are the steps involved in The Program Development Cycle.

2
Copy the following notes into your workbook.
Programming
Computer programs are written by people to solve a problem using a computer.
There are six steps involved in the Program Development Cycle. They are:
   Define the problem – you can’t solve a problem you don’t understand. You should find
out:
o The Outputs – what does the user want the program to produce?
o The Inputs – what information is needed to produce those outputs?
o The Processes – how are the inputs turned into outputs?
   Write the solution as an algorithm – an algorithm is like a recipe: it lists the steps
involved in accomplishing a task. Each step must be short enough so that it can be easily
carried out and must be performed in a particular order (sequence). The usual order is
Input, Process, Output.
   Check the algorithm – This step is the most important but is the step most often
forgotten. A desk check is used by the programmer to make sure the algorithm is correct.
A correct algorithm can be turned into a program that works. Problem solved!
   Code the algorithm in a programming language – like BASIC, Pascal or C++
   Check the program – to check that there are no syntax errors, typing errors or steps
from the algorithm accidentally omitted (left out).
   Document the program – documenting your program is really done right throughout the
program development, from the time you list the outputs to when you deliver the final
program. Documenting the program helps other programmers to understand how it works
and makes it easier to maintain the program (modify it to meet changed demands from
the users).

Paste this example into your workbook then work
through it.
Problem 1
Acme Garden Supplies sells instant lawn for \$15 per square metre and charges \$20 for
delivery. A program is required to compute the charge for customers purchasing lawn.
1) Define the Problem
Outputs – the charge to the customer – let’s call this LawnCost
Inputs – the number of square metres of lawn purchased – let’s call this LawnAmt
The Process – LawnCost = LawnAmt * 15 + 20

In the planning it is important to decide the variables needed to solve the problem. In
this case, the variables are LawnAmt and LawnCost. The names are descriptive and
help to describe the process, which helps the documentation.

Programming                                       3
Picnic Point High School
2) Write the Solution as an Algorithm
Often all this step requires is to rearrange the information above into the correct order
(Input, process, output).
Usually…
BEGIN                                              Algorithms start with a “BEGIN” and
INPUT LawnAmt                                 finish with an “END”
LET LawnCost = LawnAmt * 15 + 20              Key words are in capitals.
PRINT LawnCost                                Variable names are mixed case.
END

3) Check the Algorithm
Since this is a very simple problem using
only sequenced steps, we only need one
set of test data to do our desk check.
Choose some made up input data that
will give an answer that you know. For
this problem we’ll use a LawnAmt of 10
square metres – mainly because I can
multiply by 10. From the original
question, I calculate that 10m2 will cost \$170. Now we use a desk check table on the
algorithm to see if it gives the same output.

LawnAmt                Start by drawing a table showing every variable used
LawnCost               and include a spot for output.
Output

LawnAmt       10       Now work through the algorithm. The first line (after
LawnCost               BEGIN) is INPUT LawnAmt, so we put the value we
Output                 have chosen for LawnAmt into the table.

LawnAmt       10       The next line tells us to calculate a value for LawnCost.
LawnCost      170      Since LawnAmt in the table is 10, LawnCost is
Output                 10*15+20 or 170. Write this value in the table next to
LawnCost.

LawnAmt       10       The next line is PRINT LawnCost. Print is a word that is
LawnCost      170      used when we want output, so in the table we write the
Output        170      value of LawnCost next to output.

The next line is END so we are finished. The output is what we expected so this
algorithm appears correct!

4) Code the Algorithm in a Programming Language
We are going to use BASIC (Beginners All purpose Instruction Code) for this
program.
The following BASIC program has been written from the algorithm

PRINT “This program calculates the cost of lawn”
PRINT “Enter the number of square metres of lawn”
INPUT LawnAmt
LET LawnCost = LawnAmt * 15 + 20
PRINT “The cost is “; LawnCost

4
END
A BASIC Program
 When the BASIC program is inspected carefully, it is possible to understand
the way the computer will process the problem. A program consists of a
number of lines of code arranged in the correct order. The code contains the
instructions the computer will follow.
 The words that are contained in the program are special statements that are
recognised by the computer. The statement PRINT causes the computer to
show the message contained within the quotes to be displayed on the screen.
 When the INPUT statement is processed the computer waits for the user to
enter a value which is then stored in the memory location named LawnAmt
 After LawnAmt has been stored, the LET statement causes the computer to
perform the necessary calculation the find LawnCost. It is not necessary to
include the key word LET and this line can be written as:
LawnCost = LawnAmt * 15 + 20
 The final PRINT statement causes the message followed by the value for
LawnCost to be printed on the screen. The value of LawnCost is shown
because this part of the message was not contained within the quotes.
 To signal the end of the program the END statement is used.

Start QBASIC from the menu. When QBASIC has been loaded, you will
get a dialog box – press the escape key (Esc) to erase it then type in the
program above, pressing enter at the end of every line.

When you have finished typing in the program, choose File, SaveAs and save your
file as MOWING on your H: drive.

5) Run the Program
Select Run, Start from the menu and enter a lawn amount
of 10. If it works, go on to the next step, if not, welcome
to the world of debugging! – check your typing carefully.

6) Document the Program
There are several ways to document you program. REM statements are remark
statements that are used to explain parts of the program code. A single apostrophe
can also be used instead of the key word REM. Remarks are ignored by the computer
during processing but help make the code readable

Modify your program by adding the following lines at the beginning.
REM   *************************************************
REM   *                                               *
REM   *    A Program to Calculate the Cost of Lawn    *
REM   *           for ACME Garden Supplies            *
REM   * Written by: Your Name        on: Today’s Date *
REM   * Last Modified by: Your Name on: Today’s Date *
REM   *                                               *
REM   *************************************************

Save the program (Alt, F, S) then exit QBASIC (Alt, F, X)

Programming                                      5
Picnic Point High School
To print a listing of your program you need to open the file in Word and print it from
there. The hard copy listing is another form of documentation.

Load Word and choose File, Open from the menu. Change the “Files of Type” list
box to “All Files (*.*)”. Navigate to where you saved your program and open it.
Since your program includes your name you won’t need to add a footer. Print the
listing.

Paste the listing into your workbook and complete
the following exercises.
Exercise 1.1
Brian’s Curtains charge \$13 per metre of material and a fixed charge of \$25 when making
curtains for customers. A program is to be created to perform the calculations for the shop
owner. First the number of metres of material is needed. The cost can then be calculated by
multiplying this by 13 and adding 25.
a)      Copy and complete the following algorithm for this problem.
BEGIN
INPUT MatLength
TotalCost =     * 13 +
PRINT
END

b)     Copy and complete the following QBASIC program to perform this task.
PRINT “This program calculates the cost of curtains.”
PRINT “Enter the number of metres of material required”
INPUT .............
LET TotalCost = ................
PRINT “The total cost is \$”;.............
END

Exercise 1.2
Clive’s Hardware Shop sells nails by the gram and each gram contains 24 nails. Many
customers like to know how many nails they are receiving when they make a purchase.
a)     Copy and complete the following algorithm for this problem.
BEGIN
INPUT ……………
……….. = ………………
PRINT ………………..
END

b)     Copy and complete the following QBASIC program to perform this task.
PRINT ..............
PRINT ..............
INPUT ..............
....................
PRINT ..............
END

6
Exercise 1.3
An Insurance company pays its employees a salary of \$200 per week plus \$15 per hour for
every hour worked during the week.
a)      Design a program which will calculate the amount of pay owed to employees.
b)      Write a program to perform this task.

Exercise 1.4
A contractor who erects fences charges his customers \$14 for materials and \$9 per metre to
erect the fence. He wants a computer program to help calculate his accounts. Design and
write a program which could be used for this purpose.

Copy the following notes into your workbook.

More Sequence Programming
Using a simple sequence of steps it is possible to construct a range of very useful programs.
Problem 2
A used car company pays its sales team a weekly wage of \$300 plus 5% commission on all
sales made. A program is needed which will enable the manager to calculate the weekly
salary for his employees.
1) Define the Problem
The question only asks for salary but it would be more useful to have the name of the
employee so that the salary and name can be printed together.
Output – EmployeeName, Salary
Input – EmployeeName, SalesMade
Process – Salary = SalesMade * 5 / 100 + 300
2) Write the Solution as an Algorithm
BEGIN
Salary = SalesMade * 5 / 100 + 300
PRINT EmployeeName, Salary
END
3) Check the Algorithm
Use test data of Bob who sold \$10,000 worth of cars. He should earn \$800.
EmployeeName Bob
Salary           800
Output           Bob, 800
4) Code the Algorithm in a Programming Language
A BASIC program that could be created from this algorithm appears below:

Start QBASIC from the menu. When QBASIC has been loaded, you will
get a dialog box – press the escape key (Esc) to erase it then type in the
program above, pressing enter at the end of every line.

Type the program in carefully and when you have finished typing in the program,
choose File, SaveAs and save your file as Salary on your H: drive. Print a listing for

Programming                                      7
Picnic Point High School
PRINT “A program which calculates salary”
PRINT
INPUT “What is the employee’s name”; EmployeeName\$
PRINT “What is the value of sales for “; EmployeeName\$;
Salary = SalesMade * 5 / 100 + 300
PRINT
PRINT “The salary for “; EmployeeName\$, “is \$”; Salary
END

There are several variations in the BASIC code to that of the previous example. Read
through the code carefully and observe the following differences.

   A new form of memory storage is required for non-numeric data. The \$ after the
variable name indicates that the value will be stored as a string of characters rather
than numbers.
   The lines which contain PRINT alone will print a blank line on the screen. This is
useful for making the screen easy to read and follow.
   The INPUT statement for EmployeeName\$ prints the prompt and accepts input in the
one statement. This is the way we will be using the INPUT statement in future.
   The prompt in the INPUT statement cannot contain a variable so the print is required
to have the employee’s name before the SalesMade input. The semicolon on the end
of this line stops the display going to a new line.
   In the line where the salary is printed there are some punctuation marks. The
semicolon leaves no space between the information while the comma leaves a larger
space.
5) Run the Program
Select Run, Start from the menu and enter an employee name of Bob with 10000
worth of sales. If it works, go on to the next step, if not, welcome to the world of
debugging! – check your typing carefully.
6) Document the Program
Modify your program by adding the remark lines.
REM *************************************************
REM *                                                            *
REM *       A Program to Calculate a Salary                      *
REM * Written by: Your Name                     on: Today’s Date *
REM * Last Modified by: Your Name on: Today’s Date *
REM *                                                            *
REM *************************************************
PRINT “A program which calculates salary”
PRINT
REM ******** Data Input ********
INPUT “What is the employee’s name”; EmployeeName\$
PRINT “What is the value of sales for “; EmployeeName\$;
REM ******** Salary Calculation ********
Salary = SalesMade * 5 / 100 + 300
PRINT
PRINT “The salary for “; EmployeeName\$, “is \$”; Salary
END

8
Paste the listing into your workbook and complete
the following exercises.
Exercise 2.1
Some athletics records were recorded in feet and inches. A program is needed to take the
measurements in feet and inches and convert them to metres. There are 2.54cm to the inch,
100cm to the metre and 12 inches to the foot.
a)     Copy and complete the following algorithm for this problem.
BEGIN
INPUT NoFeet, NoInches
TotalInches = ...........* 12 + .............
TotalMetres = ................ * .................. / ..........
PRINT ................
END
b)     Copy and complete the following program.
REM .............................
REM .............................
PRINT ..........................
PRINT
REM .......................
INPUT “How many feet”; ............
INPUT “.......................”; NoInches
REM .......................
TotalInches = ...........* 12 + .............
TotalMetres = ................ * .................. /
..........
REM .......................
PRINT “..........................”; TotalMetres; “m”
Exercise 2.2
Devon Milk Supplies delivers milk to its customers and produces monthly accounts. The
products sold are milk for \$1.15 per bottle and cream for \$1.70 per carton. A program is
required to create the customer accounts.
a)     Copy and complete the following algorithm for this problem.
BEGIN
INPUT ..........., ............
Cost = .....................................
PRINT ..................
PRINT ..................
PRINT ..................
END
b)     Write a BASIC program for the above.
Exercise 2.3
When people travel overseas they need to change their money from Australian currency.
Plan and Write a program that will allow the bank teller to enter an amount of money in
Australian dollars together with the current exchange rate. The program should print out the
amount of foreign currency which the customer should receive.

Did you know that QBASIC comes with all Microsoft operating systems
since MS-DOS 5.0? For Windows 95, 98, ME, NT or 2000 you’ll find it
on the CD in a directory called OLDDOS. Copy the program and help
files to your hard drive to install it.
Paste the following notes into your workbook
and complete the exercises in your workbook.
Programming                                      9
Picnic Point High School
Good Programming Practice

You should practise good               When writing the code for computer programs,
programming practice every                there are many different variations that are
time you program                      possible in the coding stage. Even if two
programs appear to perform the same tasks,
there are some ways you can determine the better
piece of computer code. The following are some
guidelines which can be used when creating the code for
programs.

1. Choose variable names that are meaningful. For
example, P = H * R is harder to understand than
Pay = HoursWorked * Rate
2. The messages to the user should be clear and accurate.
When a user has to enter data it should be clear what
type of information they need to enter. Put in a
message that tells the user the purpose of the program.
3. When results are given they should be presented in a clear fashion with appropriate
explanations.
4. When parts of the code are different or difficult to follow, they should be explained with
a comment (REM).
5. The program should be tested carefully to make sure that it gives the correct answer in all
cases.

Exercise 3.1
The following program changes miles to kilometres. Make any changes that you consider
would help to make this a better program.
PRINT “A conversion program”
INPUT “Miles”; M
K = M * 1.609
PRINT K
END
Exercise 3.2
Sound travels at the rate of 340 metres per second in air. A program is required which will
calculate how far sound will travel in a given amount of time is the time is given in hours
and minutes. Copy and complete the following algorithm then write the program required to
perform the task outlined.
BEGIN
INPUT .........................
TotalMinutes = .............................
Distance = .....................................
PRINT ...........................................
END

10
Exercise 3.3
Poly-Finish is a paint which can be applied to driveways to renew their surface. It needs to
be applied carefully, 1 litre for every 5 square metres of driveway. It costs \$24.50 per litre.
Jones’s Hardware, which sells Poly-Finish, wishes to have a computer program to assist in
the calculation of the amount of product required and the cost. Poly-Finish is only sold in
whole litres, so your program will need to round up to the next whole litre.

Once you calculate the number of litres that will be used the following line will round up to a
whole litre:
Cans = INT(LitresNeeded + 0.999)

INT( ) is a QBASIC function that finds the integer, or whole number, part of a value. INT(6),
INT(6.1) and INT(6.9) would all be 6, as the whole number part in each case is 6. By adding
almost, but not quite 1 to the number of litres and then finding the integer part has the effect
of rounding up.
INT(6 + 0.999), or INT(6.999) is equal to 6 however INT(6.2 + 0.999) or INT(7.199) which
is 7, similarly INT(6.9 + 0.999) or INT(7.899) is 7

Work through the Program Development Cycle for this problem. Make sure your output
shows both the amount of Poly-Finish required as well as the cost for the number of cans
needed.
Exercise 3.4
The City Car Park charges clients \$0.02 for every minute a car is parked. A program is
required to assist the attendants in calculating the charge for each driver.
Design and write a program which will accept the time a car entered the car park together
with the time which it departed. The program must calculate the number of minutes the car
was parked and the parking fee owed.

Exercise 3.5
Ace Video Hire is a shop which hires out videos for \$3 per day. The manager would like to
have a computer program to assist in the running of the shop. The program he requires must
accept the customer’s name and address together with the name of the film and the number
of days it is to be hired. The program is then needed to calculate the cost of hiring and to
print an account in the following form.

----------------------------------------------------
Ace Video Hire

NAME Brian Pearce              ADDRESS 2 Hill St, Cecil Hills
FILM Rambo                     NO OF DAYS 3     COST \$9

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

Design and write a program to perform this task.

Programming                                       11
Picnic Point High School
Computer Arithmetic
Start QBASIC from the menu. When QBASIC has been loaded, you will get a
dialog box – press the escape key (Esc) to erase it.

For this exercise the immediate window will be used. It is the narrow strip at the bottom
of the screen. The cursor will probably be in the larger window above it, which is called the editing
(or view) window. If necessary, move the cursor down to the immediate window by pressing F6.

The word PRINT followed by a calculation instructs QBASIC to do the calculation and show the
result in the output window. The output window can become cluttered. The command CLS is used to
clear the screen.

No instruction will be carried out until <ENTER> is pressed.

At the bottom of the output window you will see how to get back to the immediate window because it
has an instruction at the bottom telling you to press any key to return.

To calculate the sum, difference, product and quotient of 8 and 4 you would use:
1 PRINT 8+4                              2 PRINT 8-4
3 PRINT 8*4                              4 PRINT 8/4

Your answers would be 1. 12 2. 4 3. 32 4. 2 (since * means multiply and / means divide
(also ^ means to the power of so 4^2=16 (42) \ means integer quotient and MOD gives the remainder
after division so 100 \ 15 = 6 and 100 MOD 15 = 10 ie 100/15 = 6 remainder 10))
If the cursor is not in the immediate window then press F6.
Type CLS and press <Enter>.
Press any key to return from the output window.
Type PRINT 8+4 and press <Enter>.
Read the number 12 on the output window to verify that the computer can add up.
Press any key to return from the output window.

Order of Operations
Is 6/3*2+1 equal to 5 or 2?
The computer uses the same order of operations as you should and your calculator does. You may use
this memory prompt (since you can't take your calculators into the exam)
I                                      Inner brackets
Boldly                                 Brackets
Explain                                Exponentiation
My Dear                                Multiplication and Division
Aunt Sally                             Addition and Subtraction
Loves Rats                             Left to Right
Or you can use BODMAS if you already know it.

Calculate the answers to the following. AFTER you have written YOUR (calculated in your head or
on paper) answers then, and only then, check them with the computer.
1) 7-3-2                          2) 5-2+1                      3) 4*5/2
4) 16/4/2                         5) 5*3-2                      6) 9-6/3
7) 3+4*2                          8) 9-3^2                      9) 2*4+6^2
10) 9-6^2/6                       11) 2^0                       12) 25^0.5
13) 5*(3-2)                       14) (9-6)/3                   15) 25^(1/2)
16) (16/4)/2                      17) 16/(4/2)                  18) 2*(4+6)^2
19) (2*4)+6^2                     20) (2*4+6)^2                 21) SQR(25)*2+1
22) 7 \ 2 (note the \ not /)      23) 7 MOD 2                   24) 7 MOD SQR(1+2*4)

12
Copy the following notes into your workbook.

Constants and Variables
To keep track of specific data and to allocate a spot in computer memory for that data, names
are given to quantities. These names are usually one word and should describe the item. Eg
PayRate, Number1.

A variable is a means by which values may be stored in the memory of a computer. The
value held in a variable may change during a program
eg      Counter = Counter + 1
Constants stay fixed through the program execution
eg      Payrate = 10    or Pi = 3.142

I = P * R is not as easily recognisable as Interest = Principal * Rate

Although rate may not change (it is a constant) it should not be kept as
Interest = Principal * 0.1
since the program would be hard to maintain. If the rate changed you would need to search
through the whole program looking for 0.1 and change it if it was rate and not something
else.

QBASIC Variables
In QBASIC the variable name you use shows what sort of data can be stored in it. All string
type data (that is letters or other special characters) should be enclosed in quotes or have a
variable name with \$ as the last character. eg:
Address\$ = “2 Harold St”         Part1\$= “butter”       Part2\$ = “fly”

String variables can be added as strings eg Both\$ = Part1\$ + Part2\$ and the strings are
concatenated. (both\$ = “butterfly”)

Anything that you want to treat as numbers has no \$ on the end of it’s name. eg:
Pay = 250     Position = Counter + 1        The_Answer = 7 * 6

You can not mix the two types of variables. (numeric and string) If there is a \$ on one side of
the equals sign (=) then there should be quotes on the other “” i.e. no \$ no “”.

Exercise 4.1
The following operations result in errors - state why.

Number = “42”          .....................................................................................................
Answer\$ = 50 – 8       .....................................................................................................
Help = “NRMA”          .....................................................................................................
Result = “8 + 6”       .....................................................................................................
Pay = \$250             .....................................................................................................

Programming                                                                     13
Picnic Point High School
A First Look at Loops
Every problem we have looked at so far has executed sequentially from
the first line to the last. In many problems that are solved by computer
there are a number of steps that need to be repeated. Computer languages
have special commands that allow the program execution to loop and repeat some lines a
number of times.

Many of the programs written so far would be more useful if they kept repeating. Imagine
working out the fee for 100 cars in the car park or converting 50 records! If you didn’t have
to press a key to get back to the interpreter and then run the program again it would be much
quicker.

Let’s look at the problem of averaging a set of numbers.

1) Define the Problem
Output – Average
Input – 10 numbers
Process – Add all the numbers together and divide by the number of numbers (10)

2) Write the Solution as an Algorithm
First try...
BEGIN
INPUT Number1, Number2, Number3, Number4, Number5
INPUT Number6, Number7, Number8, Number9, Number10
Sum = Number1 + Number2 + Number3 + Number4 + Number5
Sum = Sum + Number6 + Number7 + Number8 + Number9 + Number10
Average = Sum / 10
PRINT Average
END

Well, this works but it was tedious to type out. I’m glad it wasn’t 100 numbers!

Second try...
BEGIN
Note how these lines
NoOfNumbers = 10
are indented? It is
Sum = 0                                         easy to see which lines
FOR Counter = 1 TO NoOfNumbers                  are repeated.
INPUT Number
Sum = Sum + Number
NEXT Counter
Average = Sum / NoOfNumbers
PRINT Average
END

This program has more lines, but less typing and if I wanted to average 100 numbers
all I have to do is change NoOfNumbers to 100 in the first line. I have used a
FOR/NEXT loop to add the numbers together.

The line Sum = Sum + Number looks up the value of Sum from memory and the
value of Number from memory, adds them together and stores the result in the
memory location for Sum.

14
3) Check the Algorithm
The Powerpoint presentation called For-Next-
Deskcheck shows you graphically how this
deskcheck is done. Load it now and work through
it.

Copy the                        algorithm and deskcheck into your
workbook                        under the heading “Counted Loops”.

4) Code the Algorithm in a Programming Language

CLS
NoOfNumbers = 10
PRINT “A program which averages “; NoOfNumbers; “ numbers”
PRINT
Sum = 0                                   Note that these three
FOR Counter = 1 TO NoOfNumbers            lines inside the loop are
PRINT “What is number “; Counter;   indented. This makes the
INPUT Number                        program easier to read.
Sum = Sum + Number
NEXT Counter
Average = Sum / NoOfNumbers
PRINT “The average of those “; NoOfNumbers; “ is “; Average
END

Note:
   the use of a constant for the number of numbers to be averaged. This makes
the program easier to maintain. If the client wants to average 100 numbers
this program can be modified to do it with a single keystroke. If the user
decides to change the number of numbers each time the program is run then
an INPUT statement can be used to get the value of NoOfNumbers.
   the use of the PRINT statement before the INPUT of each number. The
prompt that is part of the INPUT does not allow the use of variables so we
have to use a PRINT statement to show on the screen which number to enter.

5) Run the Program
Load QBASIC and type in the above program. Use
the test data to confirm it works as expected.

Print a listing for your workbook.
6) Document the Program
Add the standard REMs at the start of your
program and for data input and output. Print a
listing for your book and highlight the loop

Programming                                  15
Picnic Point High School
Copy the following notes into your workbook filling
in the blanks as you go.
Counted Loops
Every problem before the one above has e_ _ _ _ _ _ _ s_ _ _ _ _ _ _ _ _ _ _ from the first
line to the last. In many _ _ _ _ _ _ _ _ that are solved by _ _ _ _ _ _ _ _ there are a number
of steps that need to be r_ _ _ _ _ _ _. Computer languages _ _ _ _ special commands that
allow the program _ _ _ _ _ _ _ _ _ to loop and _ _ _ _ _ _ some lines a number of times.
Problems which have loops are said to involve iteration.

In QBASIC you can use _ _ _ / _ _ _ _ loops to r_ _ _ _ _ lines of code a certain number of
times. We can write a_ _ _ _ _ _ _ _ _ with FOR/NEXT _ _ _ _ _ as well. Some computer
languages don’t have _ _ _ / _ _ _ _ loops, but there two other types of loops we can use.

The p_ _ _ _ _ _ above uses the v_ _ _ _ _ _ _ Counter to control the number of times the
loop is _ _ _ _ _ _ _ _. Counter starts at 1 and goes up by one each time the loop is done.
When _ _ _ _ _ _ _ becomes bigger _ _ _ _ the sentinal value held in the variable
NoOfNumbers the loop is not done again and program ex_ _ _ _ _ _ _ continues at the line
after the NEXT s_ _ _ _ _ _ _ _.

Complete the following exercises in your workbook.
Exercise 5.1
Copy these program lines and state their purpose.
FOR Number = 1 TO 12
PRINT Number; “ x 7 = “; Number * 7
NEXT Number
The purpose of this program is to ...

Exercise 5.2
Complete this program fragment which produces a table of the cost for cans of drink.
PRINT put a heading for the table here
FOR NoOfCans = 1 TO 24
PRINT NoOfCans, ________ * 1.2
NEXT ________

Exercise 5.4
Enter and run this program then add appropriate comments and paste the listing into your
workbook. Note the new statements READ/DATA instead of keyboard INPUT.

PRINT “Canteen Price List”
PRINT “                          Price”
FOR Item = 1 to NoOfItems
PRINT Product\$, Price
NEXT Item
END
DATA 5, soft drinks, 1.20, sport drinks, 2.50, pies, 2, hot dogs, 1.5
DATA tea/coffee, 1

16
More Loops
The counted loops we have done so far would not be able to easily cope with a
situation where the number of items to be processed was not known. Take the
car park problem – the attendant will not know at the beginning of the day
how many cars s/he will have to process. We need another type of loop.

The pre-test or WHILE loop can be used in every situation where a loop is
required. To read 10 scores and average them we could use:
Sum = 0
FOR Counter = 1 TO 10
INPUT Score
Sum = Sum + Score
NEXT Counter
Average = Sum / 10
Or we could use:
Sum = 0
Counter = 0
WHILE Counter < 10
Counter =Counter + 1
INPUT Score
Sum = Sum + Score
END WHILE
Average = Sum / 10
At this stage it looks as though the WHILE just adds three lines and more
confusion but if we don’t know how many numbers there will be to average the
WHILE structure is better:
Sum = 0                             NOTE: counter was initialised before
the loop, tested in the while
Counter = 0                         condition and incremented in the body
INPUT Score                         of the loop. It is essential that the
WHILE Score > 0                     variable that controls the loop is
Counter =Counter + 1       acted on in these three places or an
endless loop may result.
Sum = Sum + Score
INPUT Score
END WHILE
Average = Sum / Counter

The deskcheck table for the numbers 3 and 5 (average 4) is given below. The –1 value ends
the loop and is not processed.
Variable                                Value
Sum                                     0 3 8
Counter                                 0 1 2
Score                                   3 5 -1
Average                                 4
A WHILE structure
 tests the condition
 if the condition is true, then the statements between the WHILE and the END WHILE are
done once
 the condition is then retested, if it is true the statements are done again, if it is false control
passes to the next statement after the END WHILE.

Programming                                        17
Picnic Point High School
Copy the following notes into your workbook.

Pre-test or WHILE Loops
Some algorithms require a test before the task is performed or repeated. This is described as
a pre-test or WHILE loop. The repetition (loop) is performed only while the test criteria is
true. Each time, coming into the loop, the condition is tested. If it is found true, then the
process is performed, then the condition is tested again, and so on. When the condition is no
longer true the flow of control goes to the line after the loop.

A condition to be tested must have a true/false answer such as “Counter <= 10” or “Name <>
‘ZZZ’” (<> means not equal to) or “Tim_Tams_left”. The last example shows the use of a
boolean variable. Boolean variables are either true or false, so you ask “Are there Tim Tams
left?” or “Did you catch and fish” not is “CaughtFish equal to true?” Not having conditions
that result in a true or false answer is a common error by students.

The general structure of a WHILE loop for algorithms and programs is shown below.
Algorithm                                   Code
WHILE condition                            WHILE condition
Process                                    Process
END WHILE                                  WEND
Specific examples of WHILE loops are given below.
INPUT EmployeeNumber                      INPUT “Employee Number”; EmpNo
WHILE EmployeeNumber <> 0                 WHILE EmployeeNumber <> 0
INPUT Hours                           INPUT “How many hours worked”; Hours
Pay = Hours * Rate                    Pay = Hours * Rate
PRINT Pay                             PRINT “Pay them “; Pay
INPUT EmployeeNumber                  INPUT “Employee Number”; EmpNo
END WHILE                                 WEND
Counter = 1                               Counter = 1
WHILE Counter <= 12                       WHILE Counter <= 12
Answer = TableNo * Counter            Answer = TableNo * Counter
PRINT TableNo, Counter, Answer        PRINT TableNo; “ x “; Counter; “ = “; Answer
Counter = Counter + 1                 Counter = Counter + 1
END WHILE                                 WEND
Total = 0                                 Total = 0
INPUT Code                                INPUT “Please enter the code “, Code\$
WHILE Code <> T                           WHILE Code\$ <> “T”
INPUT Price                               INPUT “How much”;Price
Total = Total + Price                     Total = Total + Price
INPUT Code                                INPUT “Please enter the code “, Code\$
END WHILE                                 END WHILE
PRINT Total                               PRINT “Total of the purchases is “; Total
Enter the above code examples and modify as requested below.
Paste the resulting listings in your workbook.
Exercise 6.1
In example 1 make the Rate \$10.50 per hour. In example 2 write an INPUT
statement for TableNo.
Exercise 6.2
In example 3 what happens if t (lower case t) is entered instead of T? Use
WHILE UCASE\$(Code\$) <> “T” and try entering t again. What does UCASE\$() do?

18
Pseudocode and Flowcharts
While you understand
Get two numbers
add the numbers together
print the sum
it is not formal enough for programmers, particularly for more complex problems. Get the
two numbers from where? What is a sum?

There are several ways to describe the algorithm more formally, such as pseudocode,
flowchart and Nassi-Schneiderman Diagrams.

See handout - Comparison of Algorithm Description Methods

An algorithm is like a recipe: it lists the steps involved in accomplishing a task. An algorithm
must
 be lucid, precise and unambiguous;
 give the correct solution in all cases; and
 eventually end.

Since teams of people write most programs, algorithms must be described in a standard way
so people can work efficiently with others. The two standard ways of describing algorithms
that we will use are pseudocode and flowchart.

So far we have used pseudocode exclusively. The reason for this is that it is easy to convert
the algorithm to code and because it is too easy to make mistakes with flowchart. Flowcharts
are also difficult and time consuming to draw without a flowchart program such as Visio on
your computer. Pseudocode can be entered in any word processor.

You have probably noticed that we have used very specific words in our pseudocode. These
pseudocode key words have been in capitals and variables have been mixed case. Not all
authors use the same capitalisation and not all authors use the same key word. While we
have used INPUT at all times for data input some books may use get, read or even enter. For
output we have used PRINT but you may also see display or write.

Mathematical processes are another area where you may see differences in the way
algorithms are presented:
add exam_score to total_score means Total_score = Total_score + Exam_score
SET total_students to zero means Total_students = 0 and:
increment counter means Counter = Counter + 1

Programming languages have specific syntax. Everything has to be letter perfect for the
computer to interpret our code correctly but algorithms are written for people and only
follow general guidelines. If the logic is correct, small differences in the format of the
algorithm do not matter.

Programming                                      19
Picnic Point High School
Comparison of Algorithm Description Methods Handout
Flowchart               Pseudocode
BEGIN              BEGIN
GET number1, number2
Get number1,              LET Sum = number1 + number2
number2                 PRINT Sum
END
Sum = number1 +
number2             Nassi-Schneiderman Diagram
Get number1, number2
Print Sum        Sum = number1 + number2
print Sum
END

As you can see for such a simple problem there isn't much difference but as the examples
below show, with more complex problems the difference is a little clearer.

Pseudocode                                                       Flowchart

BEGIN
SET total_score to zero
SET total_students to zero
WHILE exam_score NOT 999
add 1 to total_students
PRINT name, exam_score
add exam_score to total_score
END WHILE
IF total_students NOT zero THEN
average_score=total_score/total_students
PRINT average_score
END IF
END

Nassi-Schneiderman Diagram

20
Flowcharts
Flowcharts are a method of representing algorithms using diagrams. They showing
operations in boxes connected by lines and arrows that graphically show the flow of control
in an algorithm.
Flowchart Elements
Flowcharts are made up of the following box types connected by lines with arrowheads
indicating the flow. Arrowheads are only needed where the flow is not top to bottom or left
to right. The elements below should be thought of as the characters of flowcharts. Just as
ordinary characters must be put together in certain ways to produce well-formed words, and
words must be put together in certain ways to produce well-structured sentences, these
flowchart elements must be connected in certain ways to form accepted structures and the
structures connected in certain ways to form well-structured algorithms.

The flowcharting structures for
sequence, repetition and selection, are
given here. These structures should be
treated like Lego blocks. Each process
box may be replaced by any of the
structures but it has to be joined only
by the top and bottom connectors.

It is considered good practice for a
single flowchart on stay on one page.
If a flowchart does not fit on one page,
use subprograms on different pages.
Subprograms on separate pages are
easier to read than using a connector to
join flowcharts over more than one
page.

Many flowcharts written by students
seem to work but can’t be programmed
because they haven’t followed the
structures given here. Avoid
flowcharts unless absolutely necessary.

Programming                                   21
Picnic Point High School
And More Loops
code fragments.

Paste listings into your workbook and write down the output that was
produced then correct the programs and paste the new listings into your book too.

Exercise 7.1
REM An infinite loop
REM press the control and break keys together to stop it
Counter = 1
WHILE Counter <= 12
Answer = TableNo * Counter
PRINT TableNo; “ x “; Counter; “ = “; Answer
WEND

Exercise 7.2
REM *** Initialisation ***
Rate = 10.5
REM *** a way of validating input ***
REM *** Note the use of two conditions joined with an OR ***
INPUT “How many hours did you work”; Hours
WHILE Hours > (7 * 24) OR Hours < 0
PRINT “That’s impossible! Please type in the number of”
PRINT “hours you worked this week. It must be a number”
PRINT “between 0 and 168 but is probably close to 40”
INPUT “How many hours did you work”; Hours
WEND
REM *** The pay calculation ***
Pay = Hours * Rate
REM *** The formatted printout ***
PRINT USING “For ### hours you get \$\$####.##”; Hours; Pay

Exercise 7.3
CLS
PRINT “                 Times Table Tester”
PRINT STRING\$(57, “=”)
PRINT “        Ten correct answers are all you need”
PRINT “A wrong answer gives you another question from that table”
PRINT “                    Good Luck!”
PRINT STRING\$(57, “=”)
RANDOMIZE TIMER
FOR Table = 1 TO 10
Number = INT(RND*12)+1 ‘chooses a random whole number between 1 & 12
PRINT “What is “; Counter; “ times “; Number;
WHILE Answer <> Counter * Number
COLOR 20
PRINT “Extra practice needed”
COLOR 7
Number = INT(RND*12)+1
PRINT “What is “; Counter; “ times “; Number;
WEND
NEXT Table

22
And Even More Loops!

Copy the following notes into your workbook.
REPEAT/UNITL Loops
In a WHILE loop (a pre test loop) a group of statements are repeated while a certain
condition is met. The REPEAT - UNTIL or POST TEST LOOP is similar in that a group of
statements are repeated. However, where the while structure tests the condition at the
beginning of the loop the repeat - until structure tests the condition at the end of the loop.
This means that the statements within the loop will be executed once before the condition is
tested. If the condition is false the statements will be repeated until the condition becomes
true.

The format for the REPEAT - UNTIL structure is:
Pseudocode                                  QBASIC Code
REPEAT                                      DO
Statement                                 Statement
Statement                                 Statement
                                         
                                         
                                         
UNTIL condition is true                     LOOP UNTIL condition is true

You can see that REPEAT - UNTIL makes the decision at the end of the loop: the statements
are executed once before the condition is tested. The QBASIC code uses different key words
to the pseudocode. The QBASIC help file lists many different ways to loop but stick to the
ways you have been shown.

There are two things that should be considered when using REPEAT - UNTIL loops:
1. There is no need for a priming read as there is in a WHILE loop. One read statement at
the beginning of the loop is sufficient. This does mean that the terminating condition is
usually processed - which may cause errors.
2. REPEAT loops repeat while the condition is false so WHILE number <> 99 is equivalent
to REPEAT ... UNTIL number = 99. When the condition becomes true the loop is not
repeated.

NOTE: If < is true then >= is false and <= is opposite to >

REPEAT loops are used less frequently because if the condition controlling the loop is a
terminal value rather than a counter, an IF statement needs to be included to prevent
processing the terminating value.

The difference between the loops can be illustrated with Tim Tams.
WHILE there are Tim Tams left                      REPEAT
Eat a Tim Tam                                      Eat a Tim Tam
END WHILE                                          UNTIL there are no Tim Tams left

Both algorithms work, unless you live in a house with no Tim Tams to start with! At that
time the post-test algorithm crashes as you try to eat a non-existent biscuit.

Programming                                     23
Picnic Point High School
Login to your computer and start QBASIC.
Type in and complete the following code
fragments. Paste the listings, with
Exercise 8.1
Counter = 1
WHILE Counter <= 10
PRINT “This is iteration number “; Counter
Counter = Counter + 1
WEND
Counter = _
DO
PRINT “This is iteration number “; Counter
Counter = Counter + 1
LOOP UNTIL Counter > __
END

Exercise 8.2
PRINT “Enter the following set of number pairs”
PRINT “1,1 3,0 0,4 0,0”
REPEAT
INPUT “Enter two numbers “, Number1, Number2
Sum = _______ + ________
PRINT Sum
UNTIL Number1 = 0 and Number2 = 0
PRINT “now enter the same set of numbers for the WHILE loop”
INPUT “Enter two numbers “, Number1, Number2
WHILE NOT (number1 = 0 AND number2 = 0)
Sum = _______ + _______
PRINT Sum
INPUT “Enter two numbers “, Number1, Number2
WEND

Exercise 8.3
INPUT “Enter the student’s name”; Student\$
WHILE UCASE\$(Student\$) <> “ZZZ”
Exam = 1
Total = 0
WHILE ____ <= 3
PRINT “Enter the score for exam “; Exam;
INPUT Score
Total = Total + _____
Exam = ____ + 1
WEND
Average = Total / 3
PRINT Student\$, Average
INPUT “______________________”; ________
WEND
PRINT “That is the end of the nested WHILE loops –“;
PRINT “press any key to continue”
WHILE INKEY\$ = “”
WEND
REM – Now write the structure above using REPEAT/UNTIL loops

24
Remember Exercise 3.4 on page 10? This example expands the
problem. Paste this example in your workbook.
The City Car Park charges clients \$0.02 for every minute a car is parked. A
program is required to assist the attendants in calculating the charge for each driver.
Design and write a program which will accept the time a car entered the car park together
with the time which it departed. The program must calculate the number of minutes the car
was parked and the parking fee (rounded to the nearest 5c) owed. Your program should keep
accepting input until 99 is entered as a time.

1) Define the Problem
Output – MinutesParked, Fee
Input – Times entering and leaving the carpark (24 hour format)
HourIn, MinuteIn, HourOut, MinuteOut             To round to the nearest 5c
Process –     TimeIn = HourIn * 60 + MinuteIn            we need to find the integer
TimeOut = HourOut * 60 + MinuteOut part of (fee*100/5)+0.5 then
MinutesParked = TimeOut – TimeIn           multiply that result by 5 and
Fee = MinutesParked * 0.02                 divide by 100. Your teacher
Fee = INT(Fee * 20+0.5)/20                 will explain this further if
Process should loop while HourIn <> 99 time and interest exists.

2) Write the Solution as an Algorithm
BEGIN
INPUT HourIn
WHILE HourIn <> 99
INPUT MinuteIn, HourOut, MinuteOut
TimeIn = HourIn * 60 + MinuteIn
TimeOut = HourOut * 60 + MinuteOut
MinutesParked = TimeOut – TimeIn
Fee = MinutesParked * 0.02
Fee = INT(Fee * 20+0.5)/20
PRINT MinutesParked, Fee
INPUT HourIn
END WHILE
END

3) Check the Algorithm
Deskcheck with in: 8:30 out: 18:40 (minutes in 610, Fee \$12.20), in: 5:00 out: 5:01 (1
min, Fee 0) and in: 5:00 out: 5:02 (2 mins, Fee \$0.05), 99
HourIn               8 5 5 99
MinuteIn             30 0 0
HourOut              18 5 5
MinuteOut            40 1 2
TimeIn               510 300 300
TimeOut              1120 301 301
MinutesParked        610 1 2
Fee                  12.2 12.2 0.02 0 0.04 0.05
Output               610 12.2 1 0 2 0.05
The output is what was expected for the input given so the algorithm is correct.

Programming                                    25
Picnic Point High School
4) Code the Algorithm in a Programming Language
PRINT “City Car Park”
PRINT
INPUT “Enter the hour the car entered (99 to end)”, HourIn
WHILE HourIn <> 99
INPUT “Now the minutes ”, MinuteIn
PRINT
PRINT “The current time is “; Time\$
INPUT “What hour are they leaving”; HourOut,
INPUT “Now the minutes “, MinuteOut
TimeIn = HourIn * 60 + MinuteIn
TimeOut = HourOut * 60 + MinuteOut
MinutesParked = TimeOut – TimeIn
Fee = MinutesParked * 0.02
Fee = INT(Fee * 20+0.5)/20
PRINT “The car was parked for “; MinutesParked
PRINT USING “Please pay \$\$##.##”; Fee
PRINT
PRINT “Press any key to continue”
WHILE INKEY\$ = “”
REM *** This loop waits till they’re ready
WEND
CLS
INPUT “Enter the hour the car entered (99 to end)”, HourIn
WEND
END
5) Run the Program
Load QBASIC and type in the above program. Use
the test data to confirm it works as expected.

Print a listing for your workbook.
6) Document the Program
Add the standard REMs at the start of your
program and for data input and output. Print a
listing for your book.

26
Try this Tricky Quick Quiz. If you can answer the
questions marked * you should do SDD!
Exercise 9.1
1    Which of the following is not a valid loop condition?
a.    WHILE A <> 0
b.    WHILE B <= 0
c.    WHILE C > 0 AND C < 100
d.    LOOP UNTIL UCASE\$(D\$) = STOP
e.    LOOP UNTIL E = 1 OR E = 2 OR E = 3

2*   Which of the following results in an infinite loop (a loop that will not stop on its
own)?
a.    WHILE A >= 0
b.    WHILE B = 10 OR B <= 0
c.    WHILE D > 0 OR D <= 100
d.    LOOP UNTIL C >= 1 AND C <= 100
e.    LOOP UNTIL UCASE(D\$) = “STOP”

3    What does the following program fragment do?
DO
INPUT “Enter Y or N: “, R\$
R\$ = UCASE\$(R\$)
LOOP UNTIL R\$ = “Y” OR R\$ = “N”

4    If A=1, B=2 and C=3, which of the following expressions are true?
a.     B*C=A+B+C
b.     A*B*C<6
c.     A < B OR A > C
d.     A < C AND A + B = C
e.     (A > B OR B > C) AND C = 3
f.     A = B OR 2 * B – 1 = C

5    Explain what is wrong with each of the following statements. The error may be a
syntax error or the statement may serve no useful purpose.
a.     WHILE A\$ = OK
b. *   WHILE B * B < 0
c.     WHILE UCASE\$(C\$) = “Continue”
d. *   WHILE D\$ <> “Y” OR D\$ <> “N”
e. *   LOOP UNTIL E < 100 OR E > 0
f. *   WHILE F > 10 AND F < 5

6    Write a loop statement for each loop condition.
a.     Continue looping while A is greater than B.
b.     Continue looping until A is greater than B.
c.     Stop looping when A is greater than B.
d. *   Continue looping while R is not 7 or 11.
e.     Continue looping while A is greater than B and C.
f.     Stop looping when A, B and C have the same value.
g. *   Continue looping until the letters in R\$ spells red or blue

Programming                                       27
Picnic Point High School
7      Deskcheck the following programs and write down the output from each.
a.   S=0                         b.    P=1
N=1                               WHILE P < 100
WHILE N < 25                           P=3*P
S=S+N                            PRINT P
PRINT N; S                  WEND
N=2*N                       END
WEND
PRINT N
END

c.    K=0                          d.    A = 128
P=1                                N=0
WHILE P < 100                      DO
K=K+1                               N=N+1
P=P*K                               A=A/2
PRINT K; P                          PRINT N; A
WEND                               LOOP UNTIL A < 5
END                                END

e.    A=0
B=1
DO
F=A+B
PRINT F
A=B
B=F
LOOP UNTIL B > 8
END

Write a program for each of the problems below...
8      Mr Getrichquik has agreed to work for you for one cent a day on the
condition that you double his wage every day. On his second day you
will pay him 2c and on his third day 4c etc. Show how much Mr
Getrichquik will be paid over the next four months.
(4 months * 4 weeks * 5 days).

9*     A list of numbers is to be typed at the keyboard. After each number other than 0 is
typed, the program should display how many numbers have been entered and the sum
of all numbers entered to that time. When the user enters 0, the average of the values
should be displayed and the program should end
10*    As above but after the average has been displayed the user should have the choice to
enter another set of numbers.
11*    Two numbers are to be typed. If the sum of the two numbers is greater than 42, the
program should display the message “The sum is greater than 42” and stop. If the
sum is not greater than 42, the program should increase the first number by 10 and
decrease the second number by 3. These new values should then be displayed and
their sum checked again. The program should repeat this process until the message is
displayed.

28
Making Choices
The Problem: Write a program to calculate pay. Adults get \$15/hour while the Juniors get
\$10/hour. The pay needs to be calculated depending on the worker's classification.

1) Define the Problem
Output: Pay
Inputs: Hours, Classification (Adult or Junior)
Process: if the classification is adult use the higher rate else use the lower rate,
Pay = Rate * Hours

2) Write the Solution as an Algorithm
BEGIN
INPUT Class, Hours
IF Class = adult THEN
Rate = 15
ELSE
Rate = 10
ENDIF
Pay = Rate* Hours
PRINT Pay
END

3) Check the Algorithm
We need at least two sets of data to
check if this algorithm works correctly.
We need one set for adult workers and
one set for junior workers. Lets use an
adult working 10 hours (\$150) and a
junior working 5 hours (\$50).

Hours            10            5
Rate             15            10
Pay              150           50
Output           150           50

See the Powerpoint presentation called Selection Deskcheck to see how this was
done.

4) Code the Algorithm in a Programming Language
PRINT “Program to calculate the pay”
INPUT “Is the worker an Adult or a Junior (A/J); Class\$
INPUT “How many hours did they work”; Hours
IF Class\$ = “A” THEN
Rate = 15
ELSE
RATE = 10
ENDIF
Programming                                       29
Picnic Point High School
Pay = Rate * Hours
PRINT “The worker receives \$”; Pay; “ pay this week.”
END

30
Note: The above program has a few usability problems, but works for all reasonable inputs
and produces the correct answer. The issues are:
 An unexpected input of “a” instead of “A” will cause the program to use the junior
rate. In fact any input other than “A” will cause the junior rate to be used.
 There is no check of the number of hours they enter.
 There is no formatting of the pay in the output.

5) Run the Program
Load QBASIC and type in the above program. Use
the test data to confirm it works as expected.

Print a listing for your workbook.
6) Document the Program
Add the standard REMs at the start of your
program and for data input and output. Validate
the inputs and format the output. Print a new
listing for your workbook and highlight the
selection.
Hint (page 26 Q3, page 25)

According to Grace M Hopper, one summer day
in 1945, the Mark 1 computer stopped working.
Computer personnel found a moth inside the
machine. They removed the offending bug, and
the computer was fine. From then on, any
mysterious problem or glitch was said to be a
bug.

Who was Grace Hopper? A true programming
pioneer. She graduated from Yale and joined the
US Naval Reserve in 1943. She was assigned to
the Bureau of Ordinance Computation Project at
Harvard, where she learned to program the first
large-scale digital computer, the Mark 1.

In 1948 she joined a private company and
became senior programmer on the team that
created the first commercial large-scale
computer, UNIVAC 1. In the 1950s she co-
authored the programming language COBOL.

She was promoted to the rank of Rear Admiral in
the Naval Reserve and died in 1992 aged 85.

Programming                                   31
Picnic Point High School
Copy the following notes and diagrams into your
workbook.

Selection (Binary)
The ability of a computer to compare two pieces of data and select one of two alternative
actions gives us the binary selection control structure. This allows us to make decisions
about what should happen next and allows for things such as negatives and different rates or
messages.

In pseudocode, the selection is represented by the keywords IF, THEN, ELSE, and ENDIF:
eg
IF student is part_time THEN
add 1 to part_time_count
ELSE
add 1 to full_time_count
ENDIF

or more generally

if nothing needs to be done in the false case
the ELSE may be omitted:
IF condition is true THEN
statement(s) in true case                 IF condition is true THEN
ELSE                                                    statement(s) in true case
statement(s) in false case                ENDIF
ENDIF

In flowcharts a decision diamond is used.

Or more generally

Complete the following exercises in your workbook.

32
Handout       Exercise

Write flowchart and pseudocode solutions to the following decisions

1) have enough money to go to the movies
2) old enough to get a learner's permit
3) set a tax rate of 30% to income above \$4567 else no tax
4) The M5 has two types of toll gate: manual, where change is given and automatic where no
change is given and the driver has to have the correct coins. Show the decision which
needs to be made about which type of gate to go through.
5) Decide if number 2 is zero before dividing number 1 by it.

Code the solution to problem 3

Assessment
Write a program to allow the user to play a number guessing game.

Programming                                   33
Picnic Point High School

```
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
 views: 11 posted: 12/5/2011 language: English pages: 33