Sei sulla pagina 1di 13

INTRODUCTION

This workbook is intended as an aid to students attempting Information Technology at the


Caribbean Examinations Council (CXC) Ordinary Level. General Proficiency as well as
Technical Proficiency students may use this workbook, as Paper I is common to both
Proficiencies.
The first section discusses algorithm development (design and analysis) and lists problems for
algorithmic solutions. The second part of the workbook lists Examination questions and provides
ample space for students response to each question. Students should understand that this
workbook is intended to provide practice for examinations and as a means of assessing their
preparedness. Responses, algorithms and programs provided are by no means the only ones
possible or feasible.
Gerard Phillip

Gerard Phillip is a teacher of Information Technology at Tranquility Government Secondary School in


Port of Spain, Trinidad. He holds a Diploma in the Teaching of Information Technology and a B.Sc
(Hons) in Computer Information Systems.

ALGORITHM DESIGN & ANALYSIS


WHAT IS AN ALGORITHM?
An algorithm is an effective procedure for solving a problem in a finite number of steps. It is
a logically sequenced series of events that would ultimately result in the solution to a given
problem. Algorithms are written prior to the writing of actual programming code. It is
essentially generic, allowing programmers to write programs in any given high-level language
(BASIC, Pascal, C+, etc.) using the same algorithm.
Algorithms contain three types of statements:
1.
Input and storage
e.g. INPUT Mark
(the score is stored in memory
location Mark)
2.
Processing
e.g. Average = Total / Count (processed by the CPU)
3.
Output e.g. PRINT Average (output to the screen/printer)
Variables
Input statements usually involve the entry of data (values) upon which processing subsequently
takes place. This data (e.g. students name; score, price of item, persons age, etc.) must be
assigned specific memory locations for storage. Since the data in memory can change (vary)
during the programs execution they are called variables.
Data is a symbolic representation of value. The values stored in variables are transformed into
information as the program is executed. Remember that algorithms are eventually converted to
high level program code.
Naming of Variables
Always give meaningful names for variables used in your algorithms. Choose names that relate
to what is being stored. This improves the programs readability and allows programmers and
other users to better understand your algorithm. Thus, if you want to store the name of a student,
then Name or Title are suitable variable names.
Algorithms show three major features:
1. Sequence (logical flow)
2. Decision (also called Selection)
3. Repetition (also called Iteration or Looping)
Sequence
Sequence means that each step or process in the algorithm must be executed in a specific order,
otherwise the algorithm will fail and the problem will not be solved. When writing an algorithm
care must be taken to state the events in the precise, logically sequenced order as they should
be executed. In the example problem I below, the Total must be found before the average score
could be calculated.

Decision
There are two decision / selection constructs: (i) IF THEN and (ii) IF ... THEN ... ELSE
(i) The IF ... THEN construct syntax:
IF (logical expression) THEN
{Statements}
Execute if expression is TRUE
This construct is used when no actions need to be performed if the expression is false.
The IF ... THEN ... ELSE construct syntax:
IF (logical expression) THEN
{Statements} executed if expression is TRUE
ELSE
{Statements} executed if expression is FALSE
END IF
This syntax uses the BLOCK IF construct and determines the execution of statements if the
expression is proven true of false. If true, then the block of statements following the IF will be
executed. If false, then the statements following the ELSE will be executed.
In our example algorithm Unsatisfactory will be printed if the expression is proven true i.e. if
the average is less than 60. If its proven to be false i.e. if the average is 60 or more, then the
ELSE statement will be executed Well done will be printed.
Relational Operators
Logical expressions include the use of comparisons using several relational symbols:
> means greater than
< means less than
In our IF . .THEN and IF ... THEN .. ELSE,
= means equal to
constructs described above, the logical
>= means greater than or equal to
expressions are actually comparisons
<= means less than or equal to
utilizing relational operators
<> means not equal to

e.g. IF age >= 18 THEN; IF cost <300.00 THEN; IF Name <> Andrew THEN
{statements}
{statements}
{statements}

e.g. Problem 1: Accept five scores obtained by a student in examinations attempted. Find and
print the average score. Should this score be less than 60 then Unsatisfactory should be
printed. Otherwise, Well done should be printed.
Algorithm:
Total = 0
Count = 0
FOR X = 1 to 5 DO
Enter marks obtained in subject # X; Mark
Sum = Sum + Mark
Count = Count + 1
END FOR
Average = Sum/Count
IF Average < 60 THEN
PRINT Average, Unsatisfactory
ELSE
PRINT Average, Well done
END IF
STOP
Nested If
The Nested If construct consists of IF.. THEN.. ELSE constructs nested inside each other:
IF (logical expression (i))THEN
IF (logical expression (ii)) THEN
IF (logical expression (n)) THEN
{ statement (if expression n is true))
ELSE
{ statement (if expression ii is true)}
ELSE
{statement (if expression i is true)}
ELSE
{statement (if all expressions are false)}
This construct is ideal when several numeric comparisons are to be made, requiring several
unique decision /selection statements of action.

e.g. Problem 2: A research laboratory recently discovered that the incubation temperature in
degrees Fahrenheit) of the eggs determined the color of the feathers of hatched chickens:
45 - 50 - yellow, 40 - 44 - white, 35 -39 - brown, 30 - 34- Beige, Under 30- Black.
Write an algorithm to accept the incubation temperature and print the color of the chickens
hatched.
Algorithm:
INPUT Temperature
IF Temperature> 29 THEN
IF Temperature> 34 THEN
IF Temperature> 39 THEN
IF Temperature> 44 THEN
PRINT Yellow Chicks
ELSE
PRINT White Chicks
ELSE
PRINT Brown Chicks
ELSE
PRINT Beige Chicks
ELSE
PRINT Black Chicks
STOP

Repetition / Looping/ Iteration


These constructs allow a statement or series of statements to be repeated any number of times..
One major advantage is that several input values can be entered without requiring the use of
several separate variables.
The FOR loop construct syntax:
FOR <counter> = <start> TO <end> STEP [Value] Do
{Statements}
ENDFOR

The statements are repeated as long as the value of the identifier specified by the <counter>
element does not exceed the value specified by <end>. A comparison is made each time the loop
iterates to check whether the <end> is exceeded. If it is not then the counter value is incremented
by one (the default step value) or by the value specified in STEP.
The FOR loop is used when the required number of iterations (loops) is known beforehand. In
example problem 1 the FOR loop is used because the problem stated the number of marks to be
entered. Thus the <end> value was set to 5. It looped five times in accepting five marks obtained
by the student. The STEP statement was not used and so the default value of 1 is in effect.

The WHILE loop


The WHILE construct Syntax
INPUT Value
WHILE (logical expression) Do
{statements } execute if Boolean argument in expression is true
INPUT value
END WHILE
The argument in the expression is tested to determine whether it is true of false. If false, the
statements will not be executed. It is therefore possible that the statements be never executed.
The loop continues indefinitely however, as long as the argument expression is true.
e.g. Problem 3: The weekly salary of employees at a company must be calculated based on the
rate of pay and the number of hours worked. No wages are calculated if a worker works for less
than 20 hours. The algorithm should print the salary of each worker.
Algorithm:
Input workers name; Name
Input rate of pay; Rate
Input number of hours worked; Hours
WHILE Hours >=20 Do
Salary = Hours * Rate
Print Name, Salary
Input workers name, Name
Input rate of pay, Rate
Input number of hours worked, Hours
END WHILE
STOP
REPEAT Loop
Repeat Loop construct syntax:
REPEAT
{statements)
UNTIL (logical expression)
The repeat loop is used to iterate or repeat a process or sequence of events until a specific
condition becomes true. The statements in the body of a Repeat loop are executed at least once
because the testing takes place at the end of the loop. Use this loop sparingly, and only when the
initial execution is desired.

E.g. Problem 4: The manager of a department store requests a program which automates cashier
service at a check-out counter. A customer may purchase several items. The total cost of
purchases should be calculated and printed after allowing for a 12% discount for items priced
under $200. Other items attract a 15% discount. The algorithm should also print the number of
items purchased. The item entry is terminated by the sentinel/dummy value 999.
Solution:
TotalCost = 0
NumItems =0
Input cost of item, Cost
WHILE Cost <>999 Do
IF Cost <200 THEN
Discount = Cost *.12
NewCost = Cost - Discount
TotalCost = TotalCost + NewCost
Num = Numltems + 1
ELSE
Discount = Cost * .15
NewCost = Cost - Discount
TotalCost = TotalCost + NewCost
Num = Numltems + 1
END IF
Input cost of item, Cost
END WHILE
PRINT Numltems, TotalCost
STOP

TotalCost = 0 and Numltems=0 are initialized


statements. They ensure that the variables
commence with no previous values stored.
The WHILE argument accepts prices of items
only if the argument returns true, i.e. only
when the price is not 999.
The statement TotalCost = TotalCost + NewCost
means to add the present value stored in TotalCost
to the present value in NewCost and place the
new sum into TotalCost.
The statement NumItems = NumItems + 1
increments the number of items purchased
by one each time an item is processed. It means
add 1 to the value stored in NumItems at present
and replace that value with the new incremented
value.

Amend the algorithm above to print the total cost of the items before discount, the total discount
and the net discounted cost. Accept a value as payment from the customer. Print this value as
well as the amount of change the customer is entitled to.
..
.
..
.
..
.
..
..
..
..
.
..
..
..

.
.
.....

.
.
.

..

ALGORITHM PROBLEMS
Algorithms
1. Write an algorithm to convert pounds
to Kilograms. (1 Kg = 2.2 lb.) The
algorithm must cater for several
conversions. Assume that at least
one conversion must be done and
the program must be terminated if the
total number of kilograms reaches or
exceeds 1000.
.....
.
.
.
.
....

2. An algorithm should accept three integer values.


The third must be over 10. If it isnt then the user
must be prompted to reenter a value. Find the sum
of the first two numbers and divide it by the third.
Print the whole number part of the answer only,
disregarding any remainder.

3. Accept any two numbers as input.


Divide the larger by the smaller.
Print the answer.


...
...
..
4. Accept the names and scores of eleven
batsmen on a cricket team.
Determine and print the names
of the batsman who scored the
most runs as well as the one who
scored the least.
..
..
..
..
..
..
..
..
..
e.g. Problem 5: Accept as input the value of sales reported by fifteen salesmen. Any salesman
repol sates in excess of 10,000 should receive a commission of 10% of his sales. Calculate and
print the sales along with the total amount of commission paid.
Algorithm:
TotalSales =0
TotalComm =0
FORX=1 to l5 Do
Enter name of salesman, Name
Enter value of sales, Sales
TotalSales = TotalSales + Sales
IF Sales> 10,000 THEN
Comm = Sales* .10
PRINT Name, Commission
TotalComm = TotalComm + Comm
END IF
END FOR
PRINT TotalSales, TotalComm
STOP
e.g. Problem 6: Write an algorithm to determine a batsmans batting statistics over the last
season. Algorithm must accept the score made each innings. The average score must be
determined and print (total score / innings played). Additionally, the number of 100s scored as

well as his highest score should be printed. The scores made should be terminated with entry of
rogue value 999.

Algorithm:
Total_Score = 0
Total Innings =0
Highest = 0
Century =0
Enter batsmans score, Runs
WHILE Runs <> 999 Do
Total_Score = TotalScore + Runs

..
..
..
..
..
..
..

Total_Innings = Total Innings + 1

..

If Runs > Highest THEN


Highest= Runs

..
..
ENDIF
..
IF Runs = 100 THEN
..
Century = Century + 1
..
END IF
..
Enter batmans score, Runs
..
END WHILE
..
Average = Total_Score / Total_Innings
..
PRINT Total_Score, Average, Highest, Century
..
STOP
..
Modify the above algorithm to determine and print the number of zeros scored, and the
number of fifties (scores between 50 and 99).

Potrebbero piacerti anche