0% found this document useful (0 votes)
24 views168 pages

Unit 7-AlgodesignAndProbsolv

The document outlines the Program Development Life Cycle, which consists of five stages: Analysis, Design, Coding, Testing, and Maintenance. It emphasizes the importance of breaking down complex problems into smaller sub-problems using methods like Top-Down Design and Stepwise Refinement, and introduces concepts such as sub-routines, flowcharts, and pseudocode for effective program design. Additionally, it covers variables, constants, data types, and the significance of clear documentation in programming.

Uploaded by

Hashir Khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views168 pages

Unit 7-AlgodesignAndProbsolv

The document outlines the Program Development Life Cycle, which consists of five stages: Analysis, Design, Coding, Testing, and Maintenance. It emphasizes the importance of breaking down complex problems into smaller sub-problems using methods like Top-Down Design and Stepwise Refinement, and introduces concepts such as sub-routines, flowcharts, and pseudocode for effective program design. Additionally, it covers variables, constants, data types, and the significance of clear documentation in programming.

Uploaded by

Hashir Khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 168

Paper 2 : UNIT 7

ALGORITHM DESIGN AND PROBLEM


SOLVING
7.1 The Program Development Life Cycle[5 stages]
• A process of investigation to find the program specification
Analysis • stages are Requirement Specification, Abstraction and
Decomposition

• uses the program specification from the analysis stage to


Design
show how the program should be developed

Coding • Writing of programs

• Is systematic checks done on an program to make sure that it


Testing
works under all conditions

• to correct issues relating to bugs in the software or to


Maintenance
resolve potential security issues.
7.1.1 Analysis

Analysis is the part of program development life cycle; a


process of investigation, leading to the specification of what a
program is required to do. It has following stages:
 Requirement Specification : Define the problem clearly. So anyone
working on the solution understands what is needed
 Abstraction : It discards unnecessary details and only keeps the key elements
 Decomposition : Breaks down the complex problem into smaller parts.
Which can even subdivided into even smaller parts
What is a Computer System

A computer system is made up of


•Software
•Data
•Hardware
•People
•Communication.
7.2.1 The Computer System and
sub-systems
• Each computer system is made up of sub-systems. Each sub-
system can be further divided into sub-systems and so on until
each sub-system performs a single task.
• Computer systems can be very large, very small or any size in
between.
Examples:
• Alarm App on mobile Small system
• Weather forecast  Very large system
7.2.1 The Computer System and its
sub-systems

• In order to understand how a computer system is built up and how it


works it is often divided up into sub-systems. This division can be shown
using top-down design to produce structure diagrams that demonstrate
the modular construction of the system.
• Each sub-system can be developed by a programmer as a sub-routine.
• How each sub-routine works can be shown by using flowcharts or
pseudocode.
Top-Down design
• Top-down design is the breaking down of a computer system into a set
of sub-systems, then breaking each sub-system down into small sub-
systems, until each sub-system just performs a single task.
Top-Down design

Top-down design is to follow these steps:


• To solve a large problem, break the problem into several smaller
tasks and work on each task separately.
• To solve each task, treat it as a new problem that can be broken
down into smaller problems.
• Repeat this process with each new task until each can be solved
without the need for any further decomposition. .
Benefits of using Top-Down Design

•Speeds up development process as more than one person can work to solve the
problem. This speeds up the development of the program.
•Different designers can work on modules individually then bring the sub-
problems together at the end.
•Each programmer can be given a module that is suitable for their area of
expertise. For example, an expert in interface design could be given the
interface modules and an expert in file-handling could be given the file-handling
modules.
•As each module is a shorter program they are easier to write, test and de-bug
than the full system.
Smartphone System Top-Down
design
The complex problem of the smartphone system was broken down
into sub-problems:
• a sub-system to manage inputs and outputs via the touch screen
• a sub-system to manage file storage
• a sub-system to manage radio transmissions.
Computer System :Smart Phone
These sub-systems also have sub-systems of their own:
• The input/output sub-system has sub-systems to update the display and
detect user input.
• The file handling sub-system has sub-systems to write data to storage and
read data from storage.
• The radio transmissions sub-system has sub-systems to manage outgoing
and incoming transmissions.
Stepwise Refinement

The process of breaking down into small sub-systems is called


stepwise refinement.
Library Routines

• A library routine is a set of programming instructions for a given task


that is already available.
• It is pre-tested and usually performs a task that is frequently required.
• Example : The task for ‘get time’ in the checking-for-the-alarm-time
algorithm
• Rnd Function in Visual Basic is used to generate a random number.
Sub-Routine

• A subroutine is a small section of a program that is part of a larger


program. For example, a game might include a subroutine to display a
high-score table.
• A subroutine is a set of programming instructions for a given task that
forms a sub-system.
• Sub-routine works can be shown by using flowcharts or pseudocode.
• Subroutines written in high-level programming languages are called
‘procedures’ or ‘functions’ depending on how they are used.
Procedure

 A small section of code that that can be called repeatedly


from different parts of program

Example

Procedure Error_msg()
Print “Invalid Data: Enter Again”
Return
Function

 A small section of code that that can be called repeatedly


from different parts of program that returns a value
Example

Function CalculateSum(a,b)
Declare c:integer
c=a+b
Return(c)
Decomposing a problem

. The component parts of any computer system are:


» inputs – the data used by the system that needs to be entered
while the system is active
» processes – the tasks that need to be performed using the input
data and any other previously stored data
» outputs – information that needs to be displayed or printed for
the users of the system
» storage – data that needs to be stored in files on an appropriate
medium for use in the future.
Example 1: An alarm app

The alarm app can be decomposed into:


» inputs – time to set the alarm, remove a previously set alarm time,
switch an alarm off, press snooze button
» processes – continuously check if the current time matches an
alarm time that has been set, storage and removal of alarm times,
management of snooze
» outputs – continuous sound/tune (at alarm time or after snooze
time expired)
» storage – time(s) for alarms set.
7.2.3 Methods used to design and
construct a solution to a problem

In order to design a solution to the problem The following methods can


be used:
» structure diagrams
» flowcharts
» pseudocode.
Structure Diagram

• Structured diagram represents a top-down design in diagrammatic form.


• It shows a design of a computer system in hierarchical way with each
level giving a more detailed breakdown of the system into sub-systems
Benefits of using Structure Diagram

• The structure diagram shows how different modules relate to each other.
This can be important in helping to visualise how a program works.
• Modules can be re-used in different programs that require the same
structure.
• Structure diagrams make it easier for another designer to understand the
logic of an algorithm.
Structure Diagram : Smart Phone
Smart Phone Sub System
• inputs and outputs via the touch screen
• file storage
• radio transmissions.
This can be represented diagrammatically as a
structure diagram (also known as a top-down
diagram). A structure diagram shows how each
system (problem) and sub-system (sub-problem)
is broken down from top to bottom. Each box is
referred to as a module.
Structure Diagram : Smart
Phone
Example Structure Diagram:
Alarm App For A Smart Phone
Alarm app

Sound
Set alarm Check time
Alarm

Turn alarm Play sound Check Reset/clear


Set time
on/off for 2 mins off/snooze alarm
Flowcharts

 A flowchart shows diagrammatically the steps required to


complete a task and the order that they are to be
performed.
 These steps, together with the order, are called an
algorithm.
 Flowcharts are an effective way to communicate how the
algorithm that makes up a system or sub-system works.
Flowcharts

• A flowchart is a way of representing the structure and flow of an


algorithm. Flowcharts show the sequence, selection and iteration within
an algorithm, Individual steps (sequence) are represented, as are the
different paths (selection) and loops (iteration) that might be followed
whilst working through the algorithm.
Example : Checking for the alarm
time
Symbols of Program Flowcharts
Advantages and disadvantages of flowcharts

Disadvantages Advantages
• They can take a lot of time to • The sequence of steps can easily seen.
produce. • Paths through the algorithm can be
easily followed.
• Changes to the algorithm mean
sections of the flowchart have to • The logic of algorithm can often be
be re-drawn understood better when represented.
• It helps others to understand how a
• Large flowcharts can become program works.
extremely complicated and
difficult to follow
Flowchart : Example

Flowchart describing
the procedure
involved in preparing
a set of envelopes for
posting.
Tasks of Drawing Flowcharts

• Draw a flowchart that will input two numbers X and Y, calculates the
sum of X and Y in Z, and display the value of Z.
• Draw a flowchart that will input two numbers in Num1 and Num2,
Compares the two numbers and outputs the bigger number.
• Draw a flowchart that will print “Hello World” 10 times.
Flow charting guidelines
Requirements should be listed in logical order.

It should be clear, neat and easy to follow.

Direction of the flow of a system is from left to right or top to bottom.

Only one flow line should come from a symbol, unless it is a decision
symbol.
Only one flow line should enter a decision symbol, but two or three flow
lines, one for each possible answer, may leave the decision symbol.
the flowchart should has a logical start and finish. It is useful to test if a
flowchart is correct by working through it with simple test data.
Drawing Flowcharts : Tasks

 Draw a flowchart that will input radius (r) and find the area of a circle(𝐴 =
𝜋𝑟 2 ) and print A.
 Draw a flowchart that will input length (L) and Breath(B) of a rectangle and
calculate Area (A=L*B). And Print A
 Draw a flowchart that will print first ten odd numbers
 Draw a flowchart that will input a number in Num and prints its table
 Draw a flowchart that will input a 10 numbers in Num and prints their sum
 Draw a flowchart that will input some numbers . If a number is >0 then it
prints “positive” if it is <0 then print “Negative”. If user enter Zero(0) then it
will end the program
Introduction

 In order to develop your skills as a programmer you need to


understand the basic principles and structures involved in
programming.
 The firmer an understanding of these basic principles you
have, the better a programmer you are likely to be.

So let us develop your understanding

34
Variables and Constants

 A variable in a computer program is a named data store


that contains a value that change during the execution of
program. E.g. count, total, largest, smallest.

35
Naming a variable

 Variables can be given almost any name, but sensible names should be
given that are connected to the data that will be stored in
 The names must not include spaces.
Variables Examples
Variables
 A variable will be created and
assigned a value at a certain point
in a program. This means the
variable can then be used
repeatedly throughout the
program, even changing its value
if it is reassigned a new one

38
Constants

 A Constant in a computer program is a named data store that


contains a value that doesn't change during the execution of
program. E.g. PI=3.142
 Constants can be very useful in programming: you only need to
change the value where the constant is defined and it will change in
every other place it is used within the program
 In order to make program understandable to others
both variables and constant should be given
meaningful names.

39
Difference between a Variable
and a Constant

The difference between a variable and a constant is that the


value stored in a variable can be changed throughout a
program, but a value stored within a constant will remain the
same throughout the progra

40
Data types

 In order for a computer to process and store data


effectively , different kinds of data are formally given
different types, this enables
 Storage of data in an appropriate way. E.g. numbers or
characters
 Effective data manipulation. E.g. numbers with
mathematical operators and characters with
concatenation.
 Automatic validation in some cases 41
Data types

Data Definition Exampl


type e
Integer It is a positive or negative whole 25, 67 -12
number that can be used with
mathematical operators
Real It is a positive or negative number 23.45, -
with a decimal point. 12.5

Character A character is any letter, number, “G”, “A”, “ ! 42


Data types

Data Definition Exampl


type e
String A series of alpha numeric characters “Hello
enclosed in quotation marks World”
Boolean A Boolean is a data-type that can True,
store one of only two values. True False
or False
Date Date data type holds a date and time 5/23/200
value 7 is 43
Declaration

 A declaration is a statement in a program that gives the


compiler or the interpreter information about a variable or
constant that is to be used in program
 A declaration ensures that sufficient memory is reserved to
store the values
Example
Declare num1, num2 : integer
Declare Std_name : string

44
What is a Pseudocode?

 Pseudocode and flowcharts are tools that a programmer may use to help
design a program, or understand one that already exists.
 Pseudocode is a method of describing the design of a system in words
 It is a list of instructions that show how the program will work.
 It uses words similar to those found in programming languages , but not
in actual strict rules of structure and Syntax.
Syntax - the rules
of a Programming
language
45
Pseudocode

 Using pseudocode is a clear and concise way to represent an algorithm.


 It resembles a mixture of English and a programming language.
 Pseudocode can be used to show people who do not know a particular
programming language how the program works.
 Once a programmer is happy with the pseudocode, it can then be written
as a program using the source code of the programming language in use.
 There is not a standard syntax for pseudocode, but there are some
commonly followed conventions.
Pseudocode

Pseudocode covers a range of programming elements:


 comments
 variables
 input and output
 selection
 iteration
 procedures and functions
 arrays
Start

Input
Algorithm Num1,Num
2

• An algorithms sets out the steps to yes


complete a given task. It is usually Num1>Nu PRINT
show as a flowchart or pseudocode. m2 Num1 is
largest
Pseudocode
No
INPUT Num1, Num2
PRINT
IF Num1 > Num2 Num2 is
THEN PRINT Num1, “is largest
largest”
ELSE PRINT Num2, “is
largest”
ENDIF End
Comments
 In pseudocode comments are written to state what a
particular line or section of code is for.
 It is just as important to comment our code when writing
pseudocode as it is when writing real code.
 Without comments, any code can be difficult to
understand.
 Too few comments can make it harder to understand a
program.
 Too many comments can make it difficult for us to find
what we are looking for in a program.
 A commented line starts with a hash symbol:
Input Pseudocode Terms

Input data means to enter any data in computers. Common


keywords used in pseudocode are
 INPUT

 GET

 OBTAIN

 READ
Output Pseudocode Terms

Output means any result that comes from a program.


Common keywords used in pseudocode are
 OUTPUT
 PRINT
 DISPLAY
 WRITE
 SHOW
Assignment

The variable on the left of the is assigned the value of the
expression on the right. For assignment either  or = sign is used.
For example cost  10 or cost =10.
 COMPUTE, CALCULATE, DETERMINE and = are use to
carry out calculations.
 SET and INIT are used to initialize variables.
 INCREMENT is used to increment a variable.

Assignment

The variable on the left of the is assigned the value of the
expression on the right. For assignment either  or = sign is used.
For example cost  10 or cost =10.
 COMPUTE, CALCULATE, DETERMINE and = are use to
carry out calculations.
 SET and INIT are used to initialize variables.
 INCREMENT is used to increment a variable.


Mathematical Operators

Symbol Action
+ Plus
- Minus
* Multiply
/ Divide
^ Exponent
PSEUDOCODE Assignment

Cost  10
Price  Cost * 2
Tax  Price * 0.12
SellingPrice Price + Tax
Gender  “M”
Chosen False
55
Activity 7.3 pg.266

56
Pseudocode writing Tasks
Q 1: Write pseudocode that takes hours(H) and minutes(M) as input, and calculates
the total number of minutes(TOTMINS) and outputs total number of minutes.
Q 2 : Write pseudocode that will
 Input two angles(ANG1 and ANG2)
 Finds and prints the third angle(ANG3) of a triangle
Using the formula
ANG3=180-(ANG1+ANG2)
Q 3 : Write pseudocode that will input temperature in centigrade (C) and converts
to Fahrenheit and prints F, using the following formula
F=1.8*C+32
57
Comparison operators

58
59
Examples of conditions

Simple Conditions Complex Conditions


Age<18
Age>12 AND Age<20
Marks>50
Gender =“M” Sum<30 OR Count<10
Title=“Mr”
Paid=“T”
Not Paid
Num<>0
Selection/Conditional Statements

These are the statements executed only when a certain


condition is satisfied
There are 2 types of selection statements
 IF.. THEN .. ELSE .. ENDIF
 CASE .. OF .. OTHERWISE .. ENDCASE
IF.. THEN .. ELSE .. ENDIF
A logical condition is tested. A positive (true) outcome
will result in the THEN statements of code being
executed. A negative (false) outcome will result in the
ELSE statements of code being executed.
Python
If Marks > =50:
PSEUDOCODE print(“Pass”)
IF Marks > =50 THEN
PRINT “Pass” else:
ELSE print(“Fail”)
PRINT “Fail”
ENDIF
IF…THEN…ELSE…ENDIF
IF (Condition)
if-code
ELSE
else-code
ENDIF
For IF statement if-code is executed if
condition is true and else-code is
executed if condition is false. ELSE
part is optional 62
If then else tasks
Q 1.Write pseudocode and draw flowchart to Input a number and check whether the number is
positive or negative an print a suitable message.
Q 2. Write pseudocode and draw flowchart to check whether a given number is even or odd
and print a suitable message.
Q 3. Write pseudocode and draw flowchart to input two integers and check whether they are
equal or not and prints a suitable message
Q 4. Write pseudocode to read the age of a candidate and determine whether it is eligible for
casting his/her own vote.
Q 5. Write an algorithm, using pseudocode , flowchart
• inputs three numbers
• outputs the largest of the three number
63
Nested IF

Nested If in Programming is placing If Statement inside


another IF Statement.
Nested If is helpful if you want to check the condition inside a
condition.
If Else Statement prints different statements based on the
expression result (TRUE, FALSE).
Sometimes we have to check even further when the condition is
TRUE or FALSE. In these situations, we can use these Nested
IF statements, but be careful while using it.
Nested IF : Flowchart
Nested IF
The algorithm below checks if a percentage mark is valid and a pass or a
fail. This makes use of two IF statements. The second IF statement is part
of the ELSE path of the first IF statement. This is called a nested IF.
Nested IF-Tasks

Q 1. Write an algorithm, using flowchart and pseudocode, that will


 inputs a number age of a person
 And prints child if Age<13, Teenager if Age is between 13 and 19, Adult
if age is between 20 and 60 and senior citizen if age is greater than 60
Q 2. Write an algorithm using pseudocode, that will input two numbers and
mathematical operator (+,-,*,/) and performs the operation depending on the
operator and displays the result

67
Nested IF-Tasks

Q 3. Write the Python program that will input the percentage marks
and print the student’s grade using the for criteria
A 80 and above
B 70 to 79
C 60 to 69
D 50 to 59
E 40 to 49
U below 40

68
CASE .. OF .. OTHERWISE ..
ENDCASE

 CASE statement is mostly used when we have number of


options (or choices) and we may need to perform a different
task for each choice. Several values are usually specified.
OTHERWISE is the path taken for all other values:
CASE .. OF .. OTHERWISE ..
ENDCASE
C.W Act 7.5 Pg. 268

71
CASE .. OF .. OTHERWISE .. ENDCASE
 VISUAL BASIC

INPUT DayNumber
CASE DayNumber OF
1: PRINT “Monday”
2: PRINT “Tuesday”
3: PRINT “Wednesday”
4: PRINT “Thursday”
5: PRINT “Friday”
6: PRINT “Saturday”
7: PRINT “Sunday”
OTHERWISE
PRINT “Invaild number”
ENDCASE
CASE .. OF .. OTHERWISE ..
ENDCASE : Q1

Write an algorithm using pseudocode, that will input marks of a students


and prints the grade.

A 75 – 100
B 65 – 74
C 55 – 64
D 45 -54
E 35 – 44
U BELOW 35

73
C.W

Write an algorithm using pseudocode, that will input two


numbers and mathematical operator (+,-,*,/) and performs
the operation depending on the operator and displays the
result (Use Case statement)

74
CASE .. OF .. OTHERWISE ..
ENDCASE – Q 3

Write an algorithm, using flowchart , that will


inputs a number between 0 and 9999
And prints how many digits a number has

75
Q 4 2210/23/O/N/19
Q The following pseudocode algorithm uses nested IF statements.
IF Response = 1 THEN
X =X + Y
ELSE
IF Response = 2 THEN
X =X – Y
ELSE
IF Response = 3 THEN
X =X * Y
ELSE
IF Response = 4 THEN
X= X / Y
ELSE
OUTPUT "No response"
ENDIF
ENDIF
ENDIF
ENDIF
(a) Name the type of statement demonstrated by the use of IF … THEN … ELSE … ENDIF [1]
(b) Re-write the pseudocode algorithm using a CASE statement.[4]
Solution

(a) Selection/Conditional Statement


(b)
CASE OF Response // CASE Response OF
1:X←X+Y
2:X←X-Y
3:X←X*Y
4:X←X/Y
OTHERWISE OUTPUT ″No response″
ENDCASE
What is a Loop?

 In computer science, a loop is a programming structure


that repeats a sequence of instructions until a specific
condition is met.
Iteration/Loops/Repetition

Iteration is the term given to the repetition of a block of statements (code) within a
computer program.
There are 3 types of iteration Iteration/Loops
 FOR .. TO .. NEXT
{Counter controlled loop}
 REPEAT .. UNTIL (Post test)
{Condition controlled loop}
 WHILE .. DO .. ENDWHILE(Pre test)
{Condition controlled loop}
When to use a loop ?

 The FOR…TO… NEXT Loop


 A set number of repetitions
 The WHILE…DO…ENDWHILE Loop
 The condition is tested at the start of the loop. A repetition where the
number of repeats is not known, that may never be completed
 The REPEAT …. UNTIL Loop
 The condition is tested at the end of the loop. A repetition, where the
number of repeats is not known, that is completed at least once

80
FOR…… NEXT Loop

 This is used when the loop is to be repeated a known fixed


number of times.
 A FOR loop keeps on carrying out a command or commands,
for a given number of times.
 The counter is automatically increased each time the loop is
performed.
 The commands to be repeated are sandwiched between the
FOR and NEXT

81
FOR .. TO .. NEXT(count-
controlled loop
FOR loop is used when the loop is to be repeated a For COUNT = 1 to 10
fixed number of times. Example : Add 10
numbers together Input NUM
TOTAL = TOTAL +
NUM Next
Output TOTAL
Example FOR…… NEXT Loop

PROBLEM: To print the numbers from 10 to 20


 ALGORITHM:
FOR number 10 TO 20
Print number
NEXT

83
Example FOR…… NEXT Loop

PROBLEM: To print the 13 times table from 1 x 13 to 10 x


13

ALGORITHM:
FOR NUMBER 1 to 10
Print 13 x NUMBER
NEXT
84
Use of Step Key Word

By default, a FOR / TO loop iterates over each value from


the start to the end in increments of 1 (one). Optionally, the
STEP keyword can be used alongside a different increment.
If specified, the loop will iterate in larger steps, in the
example below only running the loop for every other number.

For count = 1 to 10 step 2


Print Count
85
Next Count
Tasks

1. Write an algorithm using pseudocode and flowchart, that will print first 10
consecutive numbers.
2. Write an algorithm using pseudocode and flowchart, that will print first 10
Odd numbers.
3. Write an algorithm using pseudocode and flowchart, that will print first 10
Even numbers.
4. Write an algorithm using pseudocode and flowchart, that will print
numbers from 20 to 10 in reverse order
86
Tasks

5. Write an algorithm, using pseudocode which inputs 10 numbers and outputs how many of the
numbers were > 100
6. Write an algorithm using pseudocode, that will input 10 numbers and only finds the largest
number.
7. Write an algorithm using pseudocode, that will input 10 numbers and only finds the smallest
number.
8. Write an algorithm using pseudocode and flowchart, that will input 5 numbers and calculates
their total.

87
REPEAT…… UNTIL
Loop(Condition Controlled Loop

 It can also be used when we don’t know how many times


the loop is to be performed.
 The Loop is ended when certain condition is true
 The “TRUE” Condition is checked at the end of the loop .
 Therefore REPEAT LOOP has to be performed at least
once

88
REPEAT .. UNTIL Loop
.

Example: Add 10 numbers together


Count = 0
Repeat
Input NUM
TOTAL = TOTAL + NUM
COUNT = COUNT + 1
Until COUNT = 10
Output TOTAL
REPEAT .. UNTIL Loop
REPEAT LOOP Tasks
91
1. Write an algorithm using pseudocode and flowchart,
that will print first 10 consecutive numbers using
Repeat-Until Loop
2. Write an algorithm using pseudocode that will print
numbers from 10 -20 using Repeat-Until Loop
3. Write an algorithm using pseudocode that will input
numbers and calculates their sum until it exceeds 30.
Prints the sum.
4. Write an algorithm using Pseudocode that will input
some positive numbers, a negative will end the
process and finds and prints the smallest number
Task 2 : Solution

1. START
2. NUM = 10
3. REPEAT
4. PRINT NUM
5. NUM=NUM+ 1
6. UNTIL NUM>20
7. END

92
Task 4

Small =99999
Repeat
Input Num
if Num<Small AND Num>=0 then
Small =Num
end if
Until Num <0
Print Small

93
Activity

The following algorithm contains an error.


1 SET X = 1
2. REPEAT
3. X = X + 2
4. Print X
5. UNTIL X = 10
Trace the algorithm and explain what the error is.

94
WHILE… DO…ENDWHILE Loop
(Condition Controlled Loop

 It can also be used when we don’t know how many times


the loop is to be performed.
 The loop is ended when a certain condition is false.
 This condition is checked before starting the loop

95
WHILE… DO…ENDWHILE Loop
Flowchart 96
WHILE .. DO .. ENDWHILE Loop
.
Example: Add 10 numbers together
Count = 1
While count<= 10
Input NUM
TOTAL= TOTAL + NUM
COUNT = COUNT + 1
End While
Output TOTAL
Example WHILE…… DO Loop

Problem : Add 5 numbers together


Algorithm :
Count =0
TOTAL =0
While COUNT <5 DO
Input NUMBER
TOTAL  TOTAL + NUMBER
COUNT COUNT + 1
ENDWHILE
Output TOTAL

98
Task 1

Write an algorithm, using pseudocode or a program


flowchart only, that:
• inputs a series of positive numbers (-1 is used to
terminate the input),
• outputs how many numbers were less than 1000 and
• outputs how many numbers were greater than 1000.

99
Task 2

Write an algorithm using pseudocode and flowchart, that


will input some numbers and finds the largest number. Zero
will stop the input and prints the largest number
Use While Loop
Convert in Visual Basic Program

100
Wrap Up Activity

Write down the key features of


While loop
Repetitive statements
For –To - Next

Do While – End
While

Repeat - Until
FOR…… NEXT Loop Key Features

This loop is used for a known fixed number of iterations.

A FOR loop keeps on carrying out a command or commands, for a given


number of times.
The counter is automatically increased each time the loop is performed.

By default counter is incremented by 1

Increment value other than 1 can be set using STEP keyword

Initial and final values of counter are specified in the beginning of loop

The commands to be repeated are sandwiched between the FOR and NEXT
103
Repeat –Until Key features
It is a Condition Controlled Loop

It can also be used when we don’t know how many times the loop
is to be performed.
The Loop is ended when certain condition is true

The “TRUE” Condition is checked at the end of the loop .

104
Therefore REPEAT LOOP has to be performed at least once
WHILE… DO…ENDWHILE Loop

It is a Condition Controlled Loop

It can also be used when we don’t know how many times the loop is to be
performed.
Loop is executed only when condition is true

The loop is ended when a certain condition is false.

This condition is checked before starting the loop


105
Flowchart : For - Next
Flowchart : REPEAT .. UNTIL
Flowchart
: WHILE… DO…ENDWHILE 108
Syntax Of Three Loops

For - For count = initialvalue to finalvalue [Step value]


Statements
Next
Next Count

While Do While <condition> Do

End Statements
While End While

Repeat Repeat
Until Statements
Until <condition>
Examples Of Three Loops
When to use a Loops?
111

When number of repeats is fixed:


 All three loops can be used but For Loop is most efficient as there is no
need to increment the counter
 If While and Repeat loops are to be used for fixed number of iterations
then
 Condition is set on counter’s final value.
 Counter must be intialised before the loop

 Counter must be incremented inside the loop

When a condition is given:


 For loop cannot be used
 While and Repeat can be used
Differences between While and
Repeat-until

 While Loop  Repeat – Until Loop

 Condition is tested in the beginning of loop


 Condition is tested at the end of the
 Code inside the loop is executed if condition is loop
true.
 Code inside the loop is executed if
 Loop is terminated when condition becomes False condition is False
 This loop may never be executed if condition is  Loop is terminated when condition
False for the first time becomes True
 This loop is executed atleast once
Similarities between While and
Repeat-until

 Both loops are condition controlled loops


 Both loops are used when number of repeats are unknown
 Condition is tested in both types of loops
Task

Write an algorithm using pseudocode that will


 input 10 numbers
 checks whether the numbers are in the range 0 to 100
 counts how many numbers are in range and out of range
 Prints the result
Use the three types of loops

114
Homework

Q. Convert the following pseudocode from While to Repeat - Until Loop


Large = 0
Counter = 0
WHILE Counter < 30 DO
INPUT Num
IF Num> Large THEN Large = Num
Counter = Counter +1
ENDWHILE
PRINT Large
7.3 Explaining the purpose of an
algorithm

 An algorithm sets out the steps to complete a given task.


 This is usually shown as a flowchart or pseudocode, so that
the purpose of the task and the processes needed to
complete it are clear to those who study it.

116
Example 1: Output an alarm sound
117

• Waiting 10 seconds,
• Getting the current time,
• Checking the current
time with the alarm
time, and
• Outputting the alarm
 The purpose of the sound when the times
following pseudocode is to match
output the alarm sound at
the appropriate time.
The processes are:
Activity 7.6 : Page 271
118
7.4 Standard methods of solution
119
The ability to repeat existing methods is very important in the design of
algorithms; when an algorithm is turned into a program the same
methods maybe repeated many thousands of times.
Standard methods used in algorithms:
 Totalling
 Counting
 Finding maximum, minimum, and average (mean) values
 Searching using a linear search
 Sorting using a bubble sort.
7.4.1 Totalling
Totalling means keeping a total that values are
added to

Totaling is used with repetition with the total


updated every time the loop is repeated

Total = Total + Number

It may be necessary to keep a running total in a


program.
Totalling : Example

Keeping a running total of the marks awarded to each student in a class


7.4.2 Counting

Keeping a count of the number of times an action is


performed is another standard method

Counting works in a very similar way to totalling.

A variable to store the count would be created. This


variable may be originally set to 0.

Each time a process occurs 1 is added to the count. This is


done by taking the current value that is in the variable and
adding to it.
Counting : Example

Counting the number of students that were awarded a pass mark:


Example: Finding
Maximum and Minimum
Finding the largest and smallest values in a list are two standard methods
that are frequently found in algorithms, for example, finding the highest and
lowest mark awarded to a class of students.
Example : Finding the
Average
Calculating the average (mean) of all the values in a list is an extension of
the totalling method, for example, calculating the average mark for a class of
students.
7.5 Validation and verification

In order for computer systems to only accept data inputs that


are reasonable and accurate, every item of data needs to be
examined before it is accepted by the system.
Two different methods, with very similar sounding names, are
used. For data entry:
Validation ensures that only data that is reasonable is
accepted.
Verification is used to check that the data does not change as
it is being entered.

126
7.5.1 Validation

Validation is the automated checking by a program that


data is reasonable before it is accepted into a computer
system. When data is validated by a computer system, if the
data is rejected a message should be output explaining why
the data was rejected and another opportunity given to
enter the data.
Validation Checks

• Range checks
• Length checks
• Format checks
• Limit Check
• Type checks
• Character checks
• Consistency Check
• Presence check
• Check digit
Type Check
A Type Check ensures that the correct type of
data is entered into a field. It rejects characters or
symbols entered that are inconsistent with the
type of data.
A type check checks that the data entered is of a
given data type, for example, that the number of
brothers or sisters would be an integer (whole
number).
Example
The characters ‘0’ to ‘9’and ‘.’will be acceptable
for a decimal number, but alphabets and symbols
will not be.
Range Check

In range check, the program checks


that values are within particular range
of values.
Example:
In an exam marks are out of 100. The
validation rule computer can apply is
marks must be between 0 and 100
(Mark>=0 AND Marks <=100).
Limit Check

A Limit Check is similar to range check, but the rule


involves only one limit.
Example
Date_Of_Birth<=Todays date
Price>0
Length Check

In Length Check, the software checks that number of characters


entered in a string is with in specified limits. or that the data entered is
a reasonable number of characters, for example,
Examples
1.A family name could be between two and thirty characters inclusive
so that names with one character or thirty-one or more characters
would be rejected.
2. We can use a length check to enforce a minimum of 6 characters
while setting a password.
Character Check

In Character Check the software checks that a string of


characters does not contain invalid characters or symbols.
Example
A person’s name consists of alphabets or hyphen. This rule
can be applied to enter a person’s name and Dav2d can be
rejected
Format Check

In a Format Check, the software checks that a string of


characters has the required format.
A format check checks that the characters entered confirm
to a pre-defined pattern, for example, in Chapter 9 the cub
number must be in the form CUB9999.
Example
An ID code may be required in the format ‘LLL000000’
meaning three letters followed by 6 digits. So
‘AB9345550‘would be ______________
Presence Check

A Presence Check ensure that some data has been entered and the
value has not been left blank, for example, an email address for an online
transaction must be completed..
Example
In online form you have to fill the field marked with *. The forms will
not be submitted if you leave any of these fields empty.
Consistency Check

In a Consistency Check(or cross field check) the


different fields in the same record corresponds correctly.
Example
 If Ms. Entered in the title field the ‘Female’ must be
entered in Gender field
Check Digit

• A Check Digit is the final digit in a code it is calculated


from all the other digits in the code.
• Check digits are used for barcodes, product codes,
international Standard Book Numbers(ISBN) and Vehicle
identification Number(VIN)
• Check digits are used to identify the errors in data entry
caused by mis-typing or mis-scanning a barcode.

137
Verification

Verification is checking that data has been accurately copied onto the
computer or transferred from one part of the computer to another.
Verification methods include:
1. Double entry : data entered twice by different operators
2. Screen / visual check: after data entry data is rechecked from screen
before continuing
3. Parity check
4. Checksum

138
Double Entry
 For double entry the data is entered twice, sometimes by
different operators.
 The computer system compares both entries and if they
are different outputs an error message requesting that the
data is entered again.
Screen/Visual check

 A screen/visual check is a manual check completed by


the user who is entering the data.
 When the data entry is complete the data is displayed on
the screen and the user is asked to confirm that it is correct
before continuing.
 The user either checks the data on the screen against a
paper document that is being used as an input form or,
confirms whether it is correct from their own knowledge.
Activity 7.8
Concept Check

142
Match

143
Test Data

A set of test data is all the items of data required to work


through a solution
There are three types of test data:
• Normal Data
• Boundary Data
• Erroneous/Abnormal Data
144
Types Test Data

• Normal Data is what the user would normally enter.


 Stuff like 150g of Sugar for a recipe.
 This should never produce an error. (If it does your
program has some serious problems to sort out)

145
Types Test Data

 Boundary Data is almost wrong data.


 It lies on the edge of what your program is designed to
accept.
 If the program asks for a number between 0 and 10 then
boundary data would be 0 and 10 (or 1 and 9)

146
Types Test Data

• Abnormal Data is data that shouldn’t be entered.


 The user may enter it by mistake or a friend may try to
break your program for fun. e.g. entering negative
numbers for a test score

147
Testing of Data

 Testing should be thorough and complete. Several


examples of normal, extreme and invalid data should be
entered to make sure that the code works as expected.

148
Testing

• It is important to test a system in order to check it is


robust(unlikely to malfunction)
• It is very unlikely that a program will work perfectly the
first time it is run.
• Testing tries to ‘break’ the program and reveal the
presence of errors

149
7.7 Trace tables to document dry run
of algorithms

 A thorough structured approach is required to find out the


purpose of an algorithm. This involves recording and
studying the results from each step in the algorithm and
requires the use of test data and reveal the presence of
errors

150
Trace Table

A table that shows input and variables at each stage when


testing an algorithm with a dry run.
 A trace table can be used to record the results from each
step in an algorithm; it is used to record the value of an
item (variable) each time that it changes. A trace table is set
up with a column for each variable and a column for any
output. For example:
 Test data is then used to dry run the flowchart and record
the results on the trace table.
Dry Running

 The manual exercise of working through an algorithm


step by step is called a dry run. During a dry run: every
time the value of a variable is changed, the new value is
entered in that column of the trace table every time a
value is output, the value is shown in the output column.
Facts about Dry Running of
Flowcharts
It determines the
output for a known
set of data to check
it carries out the
task correctly.

Shows how variables


change their values Checks the logic of
at each stage in the algorithm.
algorithm
Advantages Of Dry Running

 In case of a mistake it is easier to back track to where the


error occurred rather than starting from the beginning
again.
 There is less chance of an error being made
7.8 Identifying errors in algorithms

Trace tables and test data can be used to identify and correct
errors.
7.9 Writing and amending
algorithms
There are a number of stages when producing an algorithm for a given
problem:
1. Problem Definition
2. Breaking Down of Problem
3. Input, Output, Process and Storage
4. Designing the Structure of Algorithm
5. Decision on Construction of the Algorithm
6. Construction of the Algorithm
7. Dry running of the Algorithm
8. Removing Errors from algorithms
•Make sure that the problem is clearly specified – the purpose of the
Problem Definition algorithm and the tasks to be completed by the algorithm

•Break the problem down in to sub-problems; – Set up processes


Breaking Down of Problem •Input, Process data, Permanent storage of data, Output of results.

Input, Output, Process and •Decide on how any data is to be obtained and stored, what is
going to happen to the data and how any results are going to be
Storage displayed.

Designing the Structure of


•Use a structure diagram.
Algorithm

Decision on Construction of the •construct your algorithm, either using a flowchart or pseudocode
Algorithm
Decision on
• construct your algorithm, either using a flowchart
Construction of or pseudocode
the Algorithm
• Use several sets of test data (Normal, Abnormal
Dry running of and Boundary) to dry run your algorithm and show
the Algorithm the results in trace tables, to enable you to find
any errors

Removing Errors • If any errors are found, correct them and repeat
the process until you think that your algorithm
from algorithms works perfectly.
Homework :
Act 7.20 pg 292
Q 2,3
Example 1: Writing algorithms in
pseudocode

Tickets are sold for a concert at $20 each. If 10 tickets are


bought then the discount is 10%, if 20 tickets are bought
the discount is 20%. No more than 25 tickets can be bought
in a single transaction.
a Use pseudocode to write the algorithm to calculate the
cost of buying a given number of tickets
b Explain how you would test your algorithm.
161
Exam-Style Questions pg. 295-298
Q 1 A solution to a problem is decomposed into its component parts.
Name and describe the component parts. [8]

1-inputs – the data used by the system that needs to be entered while the
system is active
2- processes – the tasks that need to be performed using the input data and any
other previously stored data
3- outputs – information that needs to be displayed or printed for the users of
the system
4- storage – data that needs to be stored in files on an appropriate medium for
use in the future.
Exam-Style Questions pg. 295-298
Q 1 A solution to a problem is decomposed into its component parts.
Name and describe the component parts. [8]

1-inputs – the data used by the system that needs to be entered while the
system is active
2- processes – the tasks that need to be performed using the input data and any
other previously stored data
3- outputs – information that needs to be displayed or printed for the users of
the system
4- storage – data that needs to be stored in files on an appropriate medium for
use in the future.
Q 3. A phone app is being developed to split the cost of a restaurant bill between a given number of people
It is being designed to work for up to 12 diners and for bills from $10 to $500.
a. What validation checks should be used for the number of diners and the size of the bill? [2]
b. Provide two sets of normal data and their expected results. [4]
c. Provide some abnormal/erroneous data. [1]
d. Identify the boundary data required and the expected results. [4
Q 5. The following data is to be entered onto an online form:
– Name
– Date of birth
– Password
– Phone number.
For each item state, with reasons, the validation and verification
checks that should be used on the input data
Q6 Counter Length Breadth Size Accept Reject Output
Solution Q 6Length
Counter Breadth Size Accept Reject Output

0 0 0

1 15 10 150 1

2 20 17 340 2

3 32 10 1

4 30 35 2

5 30 15 450 3

6 30 28 840 3

7 25 25 625 4

8 20 15 300 4

9 40 20 5

10 12 10 120 5 5,5,

You might also like