Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
60 views105 pages

1.1 - ProblemSolving-pseudo-page 155

This document provides an overview of algorithms design and problem solving. It discusses what an algorithm is, including that it is a precise set of steps to solve a problem and convert inputs to outputs. Problem solving techniques like defining diagrams and pseudocode are presented. The characteristics of algorithms and variables are defined. An example of calculating the sum of two values is used to demonstrate defining the problem, designing the algorithm using pseudocode, and representing it in a flowchart.

Uploaded by

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

1.1 - ProblemSolving-pseudo-page 155

This document provides an overview of algorithms design and problem solving. It discusses what an algorithm is, including that it is a precise set of steps to solve a problem and convert inputs to outputs. Problem solving techniques like defining diagrams and pseudocode are presented. The characteristics of algorithms and variables are defined. An example of calculating the sum of two values is used to demonstrate defining the problem, designing the algorithm using pseudocode, and representing it in a flowchart.

Uploaded by

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

PART1: Algorithms Design

And Problem Solving


Topic & Structure of the lesson

In this chapter you will learn about:


• Problem Solving
• Algorithm
• Pseudocode
• Flowcharts

you should be able to use these terms


correctly in your assignments and exams:

Slide 2 of 40
Problem Solving Techniques

In this chapter you will learn about:


 What are problem solving and algorithm?
 The software development method of problem
solving using computers
 Basic algorithm control structures
 The sequence structure
 The selection structure
 The repetition structure

Slide 3 of 40
What is an algorithm?

Problem 1: How do you change a wheel on car?


1. Take a spanner and loosen the wheel nuts.
2. Position a jack in an appropriate place.
3. Raise the car
4. Take off the wheel nuts and the wheel.
5. Lift replacement wheel into position.
6. Replace wheel nuts and tighten by hand.
7. Lower the car
8. Fully tighten wheel nuts.
What is an algorithm?

 For example if you tried to do step 1 after


step3, the wheel may spin and you can’t
loosen the wheel nuts and you can’t do
step 4 before step 3.
 These instructions should be followed in the
correct logical sequence.

Problem Algorithm :

A problem whose solution (Algorithm) can be


expressed as a set of executable instructions.
Algorithm
 An algorithm is a precise, step-by-step set of
instructions for solving a task.
 An algorithm does not solve a task; it gives you a
series of steps that, if executed correctly, will
result in a solution to a task.
 You use algorithms every day but you often do not
explicitly think about the individual steps of the
algorithm.
 For example, starting your car, putting on your
clothes, logging into your computer, or following a
recipe for cooking a food dish, are all accomplished
using an algorithm, a step-by-step series of actions.
What is an algorithm?

Problem 2: How do you make a cake?


1. Measure the following ingredients: 200g sugar, 200
butter, 4 eggs, 200g flour, 2 teaspoons baking powder
and 2 tablespoons of milk.
2. Mix the ingredients together in a large bowl, until the
consistency of the mixture is smooth.
3. Pour the mixture into a cake tin.
4. Bake in the oven for 20 minutes.
5. Check it is fully cooked.
6. Turn cake out of the tin and cool on a wire rack.
What is an algorithm?
 The recipe is an algorithm. The ingredients are the
input and the cake is the output. The process is
mixing the ingredients and cooking the mixture in
the oven.
 Many problems we try to solve with a computer
involve datas. The solution involves inputting
data to the computer, processing the data and
outputting results.
Problem Algorithm:

A well defined computational procedure (Algorithm)


consisting of a set of instructions, that takes some
value or set of values, as input, and produces some
value or set of values, as output.
What is an algorithm?

Algorithm : is a sequence of steps that can


be carried out to perform a task.

A algorithm is like a recipe, that converts the


ingredients into some culinary dish.
 The formal written version is a program.
 programs are the software. The machine that
runs the programs is the hardware.
Slide 9 of 40
Characteristics of an Algorithm

 Each step of an algorithm must be exactly


described.
 It must terminate, i.e. it contains a finite number of
steps.
 It must be effective, i.e.., produce the correct
output.
 It must be general, i.e.. to solve every instance of
the problem.

Slide 10 of 40
How to express an Algorithm ?
We express the algorithm using sequence of steps
written in Structure English , pseudocode and
flowchart.
Structure English: a subset of english language that
consists of command statements used to describe an
algorithm.
Pseudocode: a way of using keywords and
identifiers to describe an algorithm without
following the syntax of a particular programming
language.
A flowchart :shapes linked together to represent the
sequential steps of an algorithm.
Slide 11 of 40
pseudocode

An algorithm is usually presented in the form of some


pseudocode
which is a mixture of
•English statement,
•some mathematical notations and
•selected keywords from a programming
language
Pseudocode
Flowchart

shapes linked together to


represent the sequential
steps of an algorithm.
Problem solving

 Consider the problem below:

PROBLEM:

You are required to design a complete


system which will enable the sum of
two values to be calculated.
Problem Solving

To deal with this problem, we have to understand the


problem from the human perspective.
A question to ask yourself is this,

“How Would You Calculate the Sum of Two Values?”

Slide 16 of
Problem Solving
As the computer is also a device similar to the way in
which the human brain functions, the process of
calculating the sum of two values can also be easily
performed by the computer.

=
Slide 17 of 40
Problem Solving

Processing
(Brains)

Input

Output
Slide 18 of 40
Problem Solving
Output Device

CPU
(Brains)

Input Device
Problem Solving

Processing
5 10
5 + 10 = 15

15

Input
Output
Let us assume we are interested in calculating the sum
of 5 and 10.
Problem Solving

As shown previously, the example values (5 and 10)


have been specified explicitly.
As the brain is flexible enough in calculating a wide
range of numbers, the two input values have to be
generalised.

Slide 21 of 40
Problem Solving

Value2
Value1
Sum = Value1 + Value2

Sum

Notice that instead of using specific numbers,


variables are used to represent these values.
What Are Variables?
Variables are memory locations within the computer
which allows pieces of data to be stored.

The word variable comes from the word vary, which


means that whatever you place within a variable can
be changed.

A variable can be viewed as a container used to store


a special kind of things.

Data (for example, name,


age, salary) can be stored
in these containers.
What Are Variables?

Slide 24 of 40
Identifier name

 It is to make up names to represent the data


items that the problem uses.

 There are some usually used ‘style’ for


identifiers.

Slide 25 of 40
Identifier table

Identifer Data Type Discription


name
n INTEGER The count of numbers for the average
counting.
Number REAL …
Count INTEGER …
Total REAL Sum of the n numbers

INTEGER REAL CHAR STRING DATE CURRENCY

About Data Type we’ll discuss later.


Problem Solving

Now that we have an exact idea about how the


problem is solved, let us represent this in a clearer
manner, using the defining diagram.

Input Processing Output

Value1 Sum
Value2

Slide 27 of 40
Problem Solving
The next step is to identify the actual processing
steps required to convert the input to become the
output.

Input Processing Output

Value1 1) Read Value1, Value2 Sum


Value2 2) Calculate Sum
3) Display Sum

Slide 28 of 40
Algorithm Development
Once the defining diagram has been developed, the
next logical step is to develop the algorithm (which
is much more detailed).

Input Processing Output


1) Read Value1, Value2
Value1 Sum
2) Calculate Sum
Value2
3) Display Sum

The developed processing steps have to be more detailed


in the algorithm.
Algorithm Development

The basic mathematical operators used in


algorithms are as follows:

+ addition
- subtraction
* multiplication
/ division
= assignment
() brackets for grouping calculations
Algorithm Development

Example of an algorithm (using pseudocodes)


which can be used to carry out the tasks outlined in
the defining diagram is as follows:

1) Read Value1, Value2


2) Calculate
Sum = Value1 + Value2
3) Display Sum
Your first piece of code
Sub Main()
Rem Declare Varialbes used for store data
Dim Value1 , Value2, Sum As Integer
Rem Read Value1, Value2
Console.Write(“Value1=“)
Value1=Console.ReadLine()
Console.Write(“Value2=“)
Value2=Console.ReadLine()
Rem Calculate
Sum=Value11 +Value22
Rem Display Sum
Console.WriteLine(“ Sum=“ & Sum)
End Sub
Program Flowcharts

As humans are more inclined towards understanding


diagrams and pictures rather than words,
pseudocodes tends to become tedious to understand
if too lengthy.

flowchart :shapes linked together to represent the


sequential steps of an algorithm.

Program flowcharts, because they are represented


graphically, makes understanding easier.
Program Flowcharts (page 129)
The following are the commonly used symbols for
drawing program flowcharts.

terminator off-page
connector

process storage

decision document
making

input/output connector

Arrow heads
Program Flowcharts
Begin

Read Value1, Value2 INPUT Value1


INPUT Value2
‘Calculate
Sum  Value1 + Value2
Sum Value1 + Value2
Display Sum

OUTPUT
Sum

Raptor example : AddTwoValue.rap End


Flow chart

purchase goods in shop , If price great than


$20,there are a 20% discount else no
discount. Design a system, input price and
output Actual price should be payed.
Program Flowcharts
Begin

INPUT Price

YES Price>20.00? NO

ActualPrice * 0.80 ActualPrice

OUTPUT Actural

End
Sequence Structure
Pseudocode: Flowchart:

statement_1
Statement -1
statement_2
------------
statement_n Statement -2

Statement -n

Slide 38 of 40
Selection Structure
Flowchart:
Pseudocode:

IF condition
then-part False True
ELSE condition
else-part
ENDIF
else-part then-part

Slide 39 of 40
Selection Structure

Pseudocode:

IF condition
then-part Y
ENDIF True
condition

N
then-part
False

Slide 40 of 40
Repetition Structure

Pseudocode: Flowchart:

WHILE condition
loop-body
ENDWHILE
True
condition loop-body

False

Slide 41 of 40
Pseudocode: Flowchart:

REPEAT
loop-body
loop-body
UNTIL condition

False
condition

True

Slide 42 of 40
Task1:

 Output the first 5 square number.


 Pseudocode
N 0
REPEAT
N  N+1
A  N*N
OUTPUT N , A
UNTIL N=5

Slide 43 of 40
Task2:
INPUT a
INPUT b
INPUT c

d  b*b-4*a*c

IF d <0
THEN
Indentation OUTPUT “There are no real
roots”
White space ELSE
SquareRoot =SQRT(d)
Root1  (-b +SquareRoot) / (2*a)
Root2  (-b – SquareRoot) /2*a)
Readability OUTPUT Root1 and Root2
ENDIF
ENDIF
Slide 45 of 40
Pseudocode
A Pseudocode language is semiformal, English-like
language with a limited vocabulary that can be
used to design and describe algorithms.

The pseudocode language can be used for:


 Designing algorithms
 Communicating algorithms as programs
 Implementing algorithms as programs
 Debugging logic errors in program
Slide 46 of 40
Notes on pseudocode:

 http://en.wikibooks.org/wiki/A-level_Computing/AQ
A/Problem_Solving,_Programming,_Data_Representa
tion_and_Practical_Exercise/Problem_Solving/Pseudo
_code

Slide 47 of 40
A simple example
 An electronic toy can move over the floor
according to commands that it is given
through a keypad. As it moves, it draw a line.
 It can obey the instructions shown in the
table.
 The task is to write an algorithm for the toy
to draw a diagram which I give you .

Slide 48 of 40
Inctruciton Meaning
Forward n Move forward n cm
Backword n Move backwork n cm
Left n Turn left n degrees 10cm
Right n Turn right n degrees
Repeat n Repeat the instruction
which follows n times.
Answer: 20cm
Repeat 4 Forward 5 Right 90
Left 90 Forward 20
Repeat 3 Left 90 Forward 10

Quick Review Question


:(pseudocode) start
It usual to make sure that the toy is
back where it started and facing its
initial direction. Please Amend the
algorithm to do this . Slide 49 of 40
5cm
How to make a cup of tea
Put water in the kettle WHILE water has not boiled
wait
IF it is an electric kettle
THEN
ENDWHILE
switch the kettle
on Add water to teapot
ELSE Wait 3 minutes
put it on lit gas Pour tea into cup
ENDIF
IF there is sugar in the cup
THEN
Set up the cup and saucer stir the tea
ENDIF
Put a spoon on the saucer

Get a teapot REPEAT


Put tea in the teapot wait
UNTIL tea is cool enough to drink

IF you take sugar Drink tea!


THEN

put sugar in cup

ENDIF
Pseudocode for the Control Structures
When writing algorithms, we use four basic types of
construct:
• Assignment: A value is given a name or the value
associated with a given identifier is changed.
• Sequence: a number of steps are performed ,one
after the other
• Selection: under certain conditions some steps are
performed , otherwise different (or no) steps are
performed.
• Repetition /iteration/looping : a sequence of steps
is performed a number of times.
Assignment (coding directly)
Assignment: A value is given a name or the value
associated with a given identifier is changed.
1. Input a Number from console and print it out.
Pseudocode:

DECLARE Number AS INTEGER


OUTPUT “Please input a integer number:”
INPUT Number
OUTPUT Number

By inputting from a console , assign a value to variable Number


Assignment

2. Assign a value to a variable and print it out.

assign a value to variable Number2 directly.

Pseudocode:
DECLARE Number2 As INTEGER
Number2 10
OUTPUT Number2
Assignment

3. Copy a value from variable to another. out.

assign a value from variable Number1 to


variable Number2.

Pseudocode:
DECLARE Number1, Number2 As INTEGER
OUTPUT “Please input a integer number:”
INPUT Number1
Number2Number1
OUTPUT Number1, Number2
Assignment
4. Update a value
Input Number from console, add 1 and output

Pseudocode:

DECLARE Number AS INTEGER


OUTPUT “Please input Number:”

INPUT Number
NumberNumber+1

OUTPUT Number
Assignment
5. Swapping two value
Input two numbers from console, change value of
them and print it out.
Pseudocode:
DECLARE NumberA, NumberB ,Temp AS INTEGER
OUTPUT “Please input NumberA:”
INPUT NumberA

OUTPUT “Please input NumberB:”


INPUT NumberB

Rem swapping two values


TempNumberA
NumberANumberB
NumberBTemp

OUTPUT NumberA , NumberB


The Sequence Control Structure:

The sequence control structure is a series of


steps or statements that are executed in the
order in which they are written in an algorithm.
The Sequence Control Structure:
Problem: Convert a distance in miles and output the
equivalent distance in km. (Km=Miles * 1.61)
Identifer Data Type Explanation
Miles INTEGER Distance as a whole number of miles
Km REAL The result from using the given formular:
Km=Miles * 1.61
Pseudocode:
DECLARE Miles AS INTEGER
DECLARE Km AS REAL
OUTPUT “Enter Miles:”
INPUT Miles
Km Miles * 1.61
OUTPUT “Km:” & Km
The Selection Control Structure:
The selection control structure defines two courses of
action, depending on the outcome of a condition.
A condition is an expression that, when evaluated,
computes to either true or false.
Syntax is:
If condition then
then-part Boolean
Else Expression
else-part
End If

Slide 59 of 40
Decision Making

Being able to mimic the way the human brain


works, the computer also has the ability to make
decisions.
Decision making can be represented in
pseudocodes using the IF...THEN construct.

IF (expression) THEN
:
:
ENDIF
Decision Making—simple IF .. THEN

Example:-
We are looking for a job which pays more than
$4000.

Example of an
Boolean Expression

IF (Salary>4000) THEN
Say "I Will Take The Job!!"
ENDIF
Decision Making

Commonly used relational operators in expressions:-

> Greater Than


< Less Than Pay attention:
≥ OR ≤ etc.
= Equals To are wrong
<> Not Equals To operators
>= Greater Than or Equals To
<= Less Than or Equals To
() Brackets used for prioritising certain
calculations
Decision Making–--Normal IF .. THEN

Since all expressions works out to be either True or


False, what the IF..THEN statement represents is a two-
state condition.
For example,
A potential employer is waiting for you to give a reply
(on the spot) about the job offer with a salary of $2000.
Your decision would be to only take a job worth more
than $4000. What would you say?
IF (Salary>4000) THEN
Say “YES!”
ELSE
Say “NO!”
ENDIF
Decision Making --Complex condition

Certain conditions may give rise to more than one


expression being evaluated. These are known as
compound condition or complex condition.

Example:-
You are interested in taking up a job which pays
more than $4000 and that the company must also
provide a credit card.

IF (Salary>4000) And (CreditCard=YES) THEN


Take Job!!
ENDIF
Decision Making
Compound Boolean expression can be
represented using the following operators:-

AND Every expression must evaluate to be


true in order for the whole expression to
be true.
OR As long as any one of the expression
can be true, the entire IF statement will
be true.
NOT The inverse (opposite) of the entire
expression.
Decision Making – Nested IF .. THEN

IF statements can be nested, that is, placed


within another IF statement.
This is used in situations when the
expression is more complex than the
simple decisions (as seen earlier).

Example continue :
Give out reason if you don’t take the
job…. Slide 66 of 40
Decision Making
For example, this statement.........
IF (Salary>4000) And (CreditCard=YES) THEN
Say “Yes I Will Take The Job!!”
ENDIF
can be represented like this.........
IF (Salary>4000) THEN
IF (CreditCard=YES) THEN
Say “Yes I Will Take The Job!!”
ELSE
Say “No Credit Card?”
Say “Sorry!!”
ENDIF
ELSE
Say “Not Enough Pay!!”
ENDIF
........ whereby more possibilities can be represented.
Decision Making
For good practice...........
IF (Salary>4000) THEN
IF (CreditCard=YES) THEN
Say “Yes I Will Take The Job!!”
ELSE
Say “No Credit Card?”
Say “Sorry!!”
ENDIF
ELSE
Say “Not Enough Pay!!”
ENDIF
........ ensure that statements are properly indented
to indicate block of statements which belong
together.
Problem:Take three numbers as input and output
the largest number. (page 137)
DECLARE Number1, Number2, Number3 AS INTEGER

INPUT Number1
INPUT Number2
INPUT Number3

IF Number1>Number2 THEN
IF Number1 > Number3 THEN
OUTPUT Number1
ELSE
OUTPUT Number 3
ENDIF
ELSE
IF Number2 > Number3 THEN
OUTPUT Number2
ELSE
OUTPUT Number3
ENDIF
END IF
Another method

DECLARE BiggestSoFar, NextNumber AS INTEGER

INPUT BiggestSoFar
INPUT NextNumber

IF NextNumber>BiggestSoFar THEN
BiggestSoFarNextNumber
ENDIF

INPUT NextNumber
IF NextNumber > BiggestSoFar THEN
BiggestSoFarNextNumber
END IF

OUTPUT BiggestSoFar
Two methods compare

What are advantages of using the second


method?

1.Only two variables are used


2.The conditional statements are not nested
and do not have an ELSE part.This makes them
easier to understand.
3.This algorithm can be adapted more easily if
further numbers are to be compared
The repetition control structure
The repetition control structure specifies a block
of one or more statements that are repeatedly
executed until a condition is satisfied.
Syntax is:

WHILE condition REPEAT


loop-body
loop-body
UNTIL condition
ENDWHILE
FOR (initialze TO expression) STEP increment
Loop-body
ENDFOR Slide 72 of 40
Looping Constructs

Looping constructs (also known as repetition


or iteration constructs) are a kind of construct
found in pseudocodes which allows
statements (or a group of statements) to be
repeated.
The main reason why looping constructs are
provided is because most of the problems
which we encounter everyday requires some
degree of repetition.
Looping Constructs

An example of a process which is iterative:

Payroll processing is very much an


iterative process as the person
processing the payroll applies the same
calculations for each employee to
produce the pay slip.

Slide 74 of 40
Looping Constructs—precondition

The format of the WHILE...ENDWHILE


construct is shown below:-

Go into the loop body when expression is true

WHILE (condition)
:
:
:
ENDWHILE
An Boolean expression which
Group of
determines whether the loop will
statements
continue.
Looping Constructs— count
control

The format of the FOR...NEXT construct is


shown below:-

FOR initialze TO expression STEP increment


:
:
:
ENDFOR
Group of An expression which
statements determines whether the loop
will continue.
Looping Constructs – postcondition

The format of the REPEAT...UNTIL construct is


shown below:-
Go into the loop body until expression is true

REPEAT
:
:
:
UNTIL (expression)
Group of An expression which
statements determines whether the loop
will continue.
Looping Constructs
Take a look at the following example:-
You are required to develop a complete
system which will allow the total payroll to
be calculated.
The system is required to read in the
amount to be paid for each employee.
The moment the system receives an input
value of -99, the system is required to stop
and display the total payroll.

Rogue value : a value used to terminate a


sequence of values.
Looping Constructs

The Defining Diagram


Input Processing Output

Salary 1) Read Salary Total


2) Calculate Total
3) Display Total
Looping Constructs--Precondition

1) OUTPUT "Enter Salary"


2) INPUT Salary
3) Total  0
4) WHILE Salary<>-99
5) Total  Total + Salary
6) OUTPUT "Enter Salary"
7) INPUT Salary
8) ENDWHILE
9) OUTPUT "Total Payroll = “ & Total
Looping Constructs--Postcondition

1) Total  0
2) REPEAT
OUTPUT "Enter Salary"
INPUT Salary
Total  Total + Salary
UNTIL Salary = -99
3) OUTPUT "Total Payroll = “ & Total
What’s the difference between pre
and post condition repetition?

1.Check the condition at different place.


• precondition check it before go into
the loop body
• postcondition check it at the end of
the loop body
2. For postcondition, the loop body must run
at least once while precondition may zero
time.
Looping Constructs—fix count

Problem: print out the sum and average of


the first 10 positive integers.
DECLARE PositiveNumber ,Total , Index AS INTEGER
DECLARE Average AS REAL

Total  0
FOR Index1 TO 10
Total Total + Index
ENDFOR

Average Total /10


OUTPUT Total & “ , “ & Average
Looping Constructs—fix count

Problem: print out the sum and average of


the first 10 odd positive integers.
DECLARE OddNumber ,Total , Index AS INTEGER
DECLARE Average AS REAL

Average Total /10


OUTPUT Total & “ , “ & Average
Find the Biggest one
Problem: Input 10 non-zero positive numbers ,
and output the Biggest one.
DECLARE Biggest , Number , Index AS INTEGER

Biggest  -1

FOR Index1 TO 10
OUPUT “Input next non-zero positive number:”
INPUT Number
IF Number > Biggest THEN
Biggest  Number
ENDIF
ENDFOR

OUTPUT “The biggest one is “ & Biggest


Express fix times repetition using condition
repetition.
Express fix time repetition
Input a positive integer number n, then input n number of
integers and print the average of these numbers.(using
FOR and condition loop to realize it separately)

Slide 87 of 40
Find the Biggest one
Problem: A sequence of non-zero positive numbers is
terminated by 0. Take this sequence as input and
output the biggest number.
DECLARE Biggest , Number AS INTEGER

Biggest  -1
OUPUT “Input next non-zero positive number(0 for end):”
INPUT Number
WHILE Number <> 0
IF Number > Biggest THEN
Biggest  Number
ENDIF

INPUT Number
ENDWHILE

OUTPUT “The biggest one is “ & Biggest


Is your algorithm right?
For example:
If input data set is 78 23 90 45 8 3 0
The program should output 90

The console screen should look like below:

Input non-zero positive number(0 for end):


78
23
90
45
8
3
0
The biggest one is:90
Desk Check Table
— a method
to test algorithm

A desk check table is used to verify the correctness


of the design. This is to ensure that the program
which will eventually be developed is going to
produce the answer which is required.
The desk check table is developed based on the
following steps:-
1) Identify the data sets.
2) Identify the expected results.
3) Trace through the algorithm with the data sets
using a trace table.
4) Analyse & compare the results produced in
step (3) and the expected results in step (2).
Desk Check Table
Identify Data Sets

Input Processing Output

Value1 1) Read Value1, Value2 Sum


Value2 2) Calculate Sum
3) Display Sum

Focus on the input section of the defining diagram


and identify some possible values (data sets) which
can be used to test the system.
Desk Check Table
Identify Expected Results

Input Processing Output

Value1 1) Read Value1, Value2 Sum


Value2 2) Calculate Sum
3) Display Sum

Focus on the output section of the defining diagram


and identify some possible values which the system
will produce based on the data sets.
Desk Check Table
Trace Table - Data Set 1

Value1 Value2 Sum


Read 5 3

Calculate 8

Display 

Do the results match the expected results?


Desk Check Table
Trace Table - Data Set 2

Value1 Value2 Sum


Read 8 13

Calculate 21

Display 

Do the results match the expected results?


Desk Check Table
Trace Table - Data Set 3

Value1 Value2 Sum


Read 15 9

Calculate 24

Display 

Do the results match the expected results?


Dry –run using trace table
For example:
If input data set is 78 23 90 45 8 3 0
The program should output 90
Biggest Number Number<>0 Number>Biggest output

-1 78 False True

78 23 False False

90 False True

90 45 False False

8 False False

3 False False

0 True 90

Sequence: from left to right and from up to down


Cont’d
Example:

WHILE (income is less than 50000)


print “Enter taxable income;should be
greater than or equal to 50000”
read income
ENDWHILE

Please read this pseudocode and tell me


what this piece code do?

Input data validation


Task3:total,average

 input an integer n
 And then input a sequence of n numbers
and calculates the running total of the input
numbers.
 then outputs the average of the numbers.

Please write the pseudocode and flowchart.


Slide 98 of 40
pseudocode
n0 Validate input data .
WHILE n<=0
INPUT n Mean by validation:
ENDWHILE
• To check that data is
reasonable/acceptable
• To check data is
Total  0
complete
Count  0
REAPEAT
INPUT Number
Total Total +Number
Count  Count + 1
UNTIL Count = n
Slide 99 of 40
Questions:
 Trace the pseudocode algorithm for the
following sequence of data input:0 -5 5 2 5 4 6
3 (a trace shows how the values of the
variables change and is done using a table with
a column for each variable) .
 you should get a final output of 4. ?
 Amend the algorithm to use a REPEAT
loop( instead of the WHILE loop) and a WHILE
loop(instead of the REPEAT loop).Trace through
your solution. Slide 100 of 40
Trace Table
n Count Total Number Count=n? Total/Count
0
-5
5
0
0
2
2
1
F
5
7
2
F
4
11
Slide 101 of 40

3
Amend algorithm
REPEAT
INPUT n
Validate input data .
UNTIL n>0
Mean by validation:
• To check that data is
Total  0 reasonable/acceptable
Count  0 • To check data is
WHILE Count < n complete
INPUT Number
Total Total
+Number
Count  Count + 1
ENDWHILE

Slide 102 of 40
OUTPUT Total / n
Summary

 Problem Solving– the process of transforming the


description of a problem to its solution.
 To Solve complex problems, we use computers as a
tool and develop computer programs that give us
solutions.
 An algorithm is a sequence of a finite number of
steps arranged in a specific logical order that, when
executed, produce the solution for a problem.

Slide 103 of 40
Summary

 A pseudocode language is a semi-formal,English-


like language with a limited vocabulary that can be
used to design and describe algorithms

 Any algorithm can be described in terms of four


basic control structure. They are the assignment,
sequence, selection and repetition structure.

 A Flowchart is a graphical representation of an


algorithm.

Slide 104 of 40
Quick Review Question

1. State the difference between the WHILE –


ENDWHILE structure and the REPEATE- UNTIL
structure.

2. Write an algorithm that will display the first


hundred even numbers using the repetition.

Slide 105 of 40

You might also like