0% found this document useful (0 votes)
36 views111 pages

Chapter 12 (New Book)

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)
36 views111 pages

Chapter 12 (New Book)

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/ 111

CHAPTER 12

ALGORITHM DESIGN
AND
PROBLEM SOLVING
Topic Chapter 12
Computational Thinking Algorithm Design and Problem Solving

 12.01 WHAT IS COMPUTATIONAL THINKING?

• COMPUTATIONAL THINKING IS A PROBLEM-SOLVING


PROCESS WHERE A NUMBER OF STEPS ARE TAKEN IN ORDER
TO REACH A SOLUTION. IT IS A LOGICAL APPROACH TO
ANALYZING A PROBLEM, PRODUCING A SOLUTION THAT CAN
BE UNDERSTOOD BY HUMANS AND USED BY COMPUTERS.
• COMPUTATIONAL THINKING INVOLVES FOUR KEY STRANDS:
 ABSTRACTION
DECOMPOSITION DATA MODELING
PATTERN RECOGNITION
ALGORITHMIC THINKING
Topic Chapter 12
Abstraction Algorithm Design and Problem Solving

ABSTRACTION INVOLVES FILTERING OUT INFORMATION


THAT IS NOT NECESSARY TO SOLVE A PROBLEM.
ABSTRACTION GIVES US THE POWER TO DEAL WITH
COMPLEXITY.
AN ALGORITHM IS AN ABSTRACTION OF A PROCESS
THAT TAKES INPUTS, EXECUTES A SEQUENCE OF
STEPS, AND PRODUCES OUTPUTS.
AN ABSTRACT DATA TYPE DEFINES AN ABSTRACT SET
OF VALUES AND OPERATIONS FOR MANIPULATING
THOSE VALUES.
Topic Chapter 12
Decomposition Algorithm Design and Problem Solving

DECOMPOSITION MEANS BREAKING PROBLEMS DOWN


INTO SUB-PROBLEMS IN ORDER TO EXPLAIN A PROCESS
MORE CLEARLY.
DECOMPOSITION LEADS US TO THE CONCEPT OF
PROGRAM MODULES USING:
 PROCEDURES AND
 FUNCTIONS
Topic Chapter 12
Data modeling Algorithm Design and Problem Solving

DATA MODELING INVOLVES ANALYZING AND ORGANIZING


DATA.
WE CAN SET UP ABSTRACT DATA TYPES TO MODEL REAL-
WORLD CONCEPTS, SUCH AS QUEUES OR STACKS.
WHEN A PROGRAMMING LANGUAGE DOES NOT HAVE
SUCH DATA TYPES BUILT-IN, WE CAN DEFINE OUR OWN BY
BUILDING THEM FROM EXISTING DATA TYPES.
Topic Chapter 12
Pattern recognition Algorithm Design and Problem Solving

PATTERN RECOGNITION MEANS LOOKING FOR PATTERNS OR COMMON


SOLUTIONS TO COMMON PROBLEMS AND USING THESE TO COMPLETE TASKS
IN A MORE EFFICIENT AND EFFECTIVE WAY.
THERE ARE MANY STANDARD ALGORITHMS TO SOLVE STANDARD PROBLEMS,
SUCH AS SORTING OR SEARCHING .
Topic Chapter 12
Algorithm design Algorithm Design and Problem Solving

• ALGORITHM DESIGN INVOLVES DEVELOPING STEP-BY-STEP


INSTRUCTIONS TO SOLVE A PROBLEM.

• WHAT IS AN ALGORITHM?
- A SEQUENCE OF DEFINED STEPS THAT CAN BE
PERFORMED TO CARRIED OUT TO PERFORM A TASK.
Topic Chapter 12
Algorithm Design and Problem Solving
Algorithm design

• WE USE ALGORITHMS IN EVERYDAY LIFE. FOR EXAMPLE, IF


YOU WANT TO BAKE A CAKE, YOU FOLLOW A RECIPE.
1. MEASURE THE FOLLOWING INGREDIENTS: 200G SUGAR,
200G 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.
Topic Chapter 12
Algorithm Design and Problem Solving
Algorithm design

4. BAKE IN THE OVEN AT 190° C FOR 20 MINUTES.


5. CHECK IF IT IS FULLY COOKED.
6. TURN CAKE OUT OF THE TIN AND COOL ON A WIRE RACK.
 THE RECIPE IS AN ALGORITHM.
 THE INGREDIENTS ARE THE INPUT AND THE CAKE IS THE FINAL OUTPUT.
 THE PROCESS IS MIXING THE INGREDIENTS AND BAKING THE CAKE IN THE
OVEN.
Topic Chapter 12
Basic Program Operations Algorithm Design and Problem Solving

• THE SOLUTION OF A PROBLEM INVOLVES INPUTTING DATA


TO THE COMPUTER, PROCESSING THE DATA AND
OUTPUTTING RESULTS (AS SHOWN IN FIGURE 12.03).
Topic Chapter 12
Algorithm Design and Problem Solving
Algorithm design

• SOMETIMES A STEP MIGHT NEED BREAKING DOWN INTO


SMALLER STEPS. FOR EXAMPLE, STEP 2 CAN BE MORE DETAILED.
• STEP 2: . MIX THE INGREDIENTS TOGETHER IN A LARGE BOWL,
UNTIL THE CONSISTENCY OF THE MIXTURE IS SMOOTH.
• 2.1 BEAT THE SUGAR AND BUTTER TOGETHER UNTIL ITS FLUFFY.
• 2.2 ADD THE EGGS, ONE AT A TIME, MIXING CONSTANTLY.
• 2.3 SIEVE THE FLOUR AND BAKING POWDER AND STIR SLOWLY
INTO THE EGG MIXTURE.
• 2.4 ADD MILK AND MIX TO GIVE A CREAMY CONSISTENCY.
Topic Chapter 12
Algorithm Design and Problem Solving
Branches of algorithm

 BRANCHES OF ALGORITHM:

i. FLOWCHART
ii. PSEUDOCODE
Topic Chapter 12
Algorithm Design and Problem Solving
Expressing algorithms

 12.03 EXPRESSING ALGORITHMS:

IN COMPUTER SCIENCE, WHEN WE DESIGN (THE ALGORITHM)


USING SEQUENCES OF STEPS WRITTEN IN STRUCTURED ENGLISH
OR PSEUDOCODE.
 STRUCTURED ENGLISH IS A SUBSET OF THE ENGLISH
LANGUAGE AND CONSISTS OF COMMAND STATEMENTS.
 PSEUDOCODE RESEMBLES A PROGRAMMING LANGUAGE
WITHOUT FOLLOWING THE SYNTAX OF A PARTICULAR
PROGRAMMING LANGUAGE.
 A FLOWCHART IS AN ALTERNATIVE METHOD OF REPRESENTING
AN ALGORITHM. A FLOWCHART CONSISTS OF SPECIFIC SHAPES,
LINKED TOGETHER.
Topic Chapter 12
Flow chart shapes Algorithm Design and Problem Solving

• DRAW A FLOWCHART FOR CAKE BAKING PROBLEM.


FOUR BASIC TYPES OF CONSTRUCTS IN
ALGORITHM
• ASSIGNMENT
• SEQUENCE
• SELECTION
• ITERATION/LOOPING/
REPETITION
Topic Chapter 12
Basic constructs in Algorithm Algorithm Design and Problem Solving

 ASSIGNMENT: INSTRUCTION IN A PROGRAM THAT PLACES A VALUE INTO A SPECIFIED


VARIABLE

 SEQUENCE: PROGRAMMING STATEMENTS ARE EXECUTED CONSEQUENTLY, AS THEY APPEAR


IN THE

PROGRAM

 SELECTION: CONTROL STRUCTURE IN WHICH THERE IS A TEST TO DECIDE IF CERTAIN


INSTRUCTIONS ARE

EXECUTED.

O IF SELECTION: TESTING 2 POSSIBLE OUTCOMES

O CASE SELECTION: TESTING MORE THAN 2 OUTCOMES

 REPETITION/ITERATION: CONTROL STRUCTURE IN WHICH A GROUP OF STATEMENTS IS


EXECUTED REPEATEDLY.

O FOR LOOP: IT IS ALSO CALLED COUNT – CONTROL LOOP; EXECUTED A SET


NUMBER OF

TIMES

O WHILE LOOP: CONDITIONAL; EXECUTED BASED ON CONDITION AT START OF


Topic Chapter 12
Algorithm Design and Problem Solving
Branches of algorithms

• FLOWCHARTS WERE THE FIRST DESIGN TOOL TO


BE WIDELY USED, BUT UNFORTUNATELY THEY DO
NOT REFLECT SOME OF THE CONCEPTS OF
STRUCTURED PROGRAMMING VERY WELL.
• PSEUDOCODE, ON THE OTHER HAND, IS A NEWER
TOOL AND HAS FEATURES THAT MAKE IT MORE
REFLECTIVE OF THE STRUCTURED PROGRAMMING
CONCEPTS.
Topic Chapter 12
Flow chart shapes Algorithm Design and Problem Solving
Topic Chapter 12
Flow chart Algorithm Design and Problem Solving
Topic Chapter 12
Flow chart Algorithm Design and Problem Solving
SEQUENCE

 REAL LIFE EXAMPLE OF MAKING A CUP OF TEA, WE USE SEQUENCE OF


STEPS AS FOLLOWS:

• ORGANISE EVERYTHING TOGETHER


• PLUG IN KETTLE
• PUT TEA BAG IN CUP
• PUT WATER INTO KETTLE
• WAIT FOR KETTLE TO BOIL
• ADD WATER TO CUP
• REMOVE TEABAG WITH SPOON/FORK
• ADD MILK AND/OR SUGAR
• SERVE TEA
SEQUENCE

 IN PSEDUCODE, WE USE SEQUENCE AS FOLLOWS:

PROBLEM: TAKE TWO NUMBER A AND B AS INPUT AND PRINT SUM


OF THESE TWO NUMBERS.

• INPUT A
• INPUT B
• SUM  A + B
• PRINT SUM
SELECTION
TYPES OF SELECTION

Selection

IF… CASE
ELSE..END OF..OTHERWISE..EN
IF D CASE
SELECTION

• WHAT IF WE WANT TO MAKE A CHOICE, FOR EXAMPLE, DO WE WANT TO ADD


SUGAR OR NOT TO THE TEA?
SELECTION

• WHAT IF WE WANT TO MAKE A CHOICE, FOR EXAMPLE, DO WE WANT TO ADD


SUGAR OR NOT TO THE TEA?
• WE CALL THIS SELECTION.
SELECTION
 REAL LIFE EXAMPLE OF MAKING A CUP OF TEA, WE USE SEQUENCE OF STEPS AS FOLLOWS:

• ORGANISE EVERYTHING TOGETHER


• PLUG IN KETTLE
• PUT TEA BAG IN CUP
• PUT WATER INTO KETTLE
• WAIT FOR KETTLE TO BOIL
• ADD WATER TO CUP
• REMOVE TEABAG
• IF YOU LIKE TO HAVE MILK?
• IF THE ANSWER IS YES, ADD MILK OR IF NO DO NOTHING
• IF YOU LIKE TO HAVE SUGAR?
• IF THE ANSWER IS YES, ADD SUGAR OR IF NO DO NOTHING
• SERVE TEA
SELECTION

• SYNTAX OF WRITING SELECTION IN PSEUDOCODE IS AS


FOLLOWS:

IF (<CONDITION>)
THEN <STATEMENTS>
ELSE <STATEMENTS>
ENDIF
SELECTION
• SO LET’S SAY WE WANT TO EXPRESS THE FOLLOWING
ALGORITHM TO PRINT OUT THE BIGGEST OF ANY TWO
NUMBERS:

• READ TWO NUMBERS, CALL THEM A AND B.


IF A IS BIGGER THAN B, PRINT OUT A,
OTHERWISE PRINT OUT B.
PSEUDOCODE

INPUT OR READ A
 All the syntax of
INPUT OR READ B keywords should be all
capital which are shown
IF (A > B) THEN as blue colour in the
diagram
PRINT OR OUTPUT A
ELSE
PRINT OR OUTPUT B
ENDIF
SELECTION

• SO LET’S SAY WE WANT TO EXPRESS THE FOLLOWING


ALGORITHM TO PRINT OUT THE BIGGER OF THREE
NUMBERS:

• READ THREE NUMBERS, CALL THEM A, B


AND C.
• IF A IS BIGGER THAN B, THEN IF A IS BIGGER
THAN C, PRINT OUT A, OTHERWISE PRINT OUT
C.
• IF B IS BIGGER THAN A, THEN IF B IS BIGGER
THAN C, PRINT OUT B, OTHERWISE PRINT OUT
SELECTION

INPUT OR READ A
INPUT OR READ B
INPUT OR READ C
IF (A > B)THEN // A IS BIGGER THAN B
IF (A > C) THEN // A IS BIGGER THAN C
PRINT A // A IS BIGGEST
ELSE
PRINT C // C IS BIGGEST
ENDIF
ELSE // B IS BIGGER THAN A
IF (B > C)THEN // B IS BIGGER THAN C
PRINT B // B IS BIGGEST
ELSE
PRINT C // C IS BIGGEST
ENDIF
ENDIF
 PSEUDOCODE FORMAT: SELECTION
CASE ….OF…OTHERWISE…
ENDCASE CASE….ENDCASE
• EXAMPLE:
INPUT MARKS
CASE OF MARKS
CASE 0 TO 39
PRINT “FAIL”
CASE 40 TO 59 Marks Output Message
PRINT “PASS” 0 - 39 “FAIL”
CASE 60 TO 79
40 - 59 “PASS”
PRINT “CREDIT”
CASE 80 TO 100 60 - 79 “CREDIT”
PRINT “DISTINCTION” 80 - 100 “DISTINCTION”
OTHERWISE
Marks more than “INVALID
PRINT “INVALID MARKS“ 100 and less than MARKS“
ENDCASE 0
Topic Chapter 12
Variables Algorithm Design and Problem Solving

12.04 WHEN WE INPUT DATA FOR A PROCESS, INDIVIDUAL


VALUES NEED TO BE STORED IN MEMORY.
WE NEED TO BE ABLE TO REFER TO A SPECIFIC MEMORY
LOCATION SO THAT WE CAN WRITE STATEMENTS OF WHAT
TO DO WITH THE VALUE STORED THERE.
WE REFER TO THESE NAMED MEMORY LOCATIONS AS
VARIABLES.
Topic Chapter 12
Variables Algorithm Design and Problem Solving

 For example, the variable used to store a count of how many guesses have
been made in a number guessing game might be given the identifier
NUMBEROFGUESSES and the player’s name might be stored in a variable
called THISPLAYER, shown in figure 12.04.

you can imagine these variables like boxes with name labels on them. when a
value is input, it is stored in the box with the specified name (identifier) on it.
Topic Chapter 12
Identifier Naming Conventions Algorithm Design and Problem Solving

 IDENTIFIER NAME SHOULD NOT CONTAIN SPACES, ONLY


LETTERS, DIGITS AND _ (THE UNDERSCORE SYMBOL)
 TO MAKE ALGORITHMS EASIER TO UNDERSTAND, THE
NAMING OF A VARIABLES SHOULD REFLECT THE VARIABLE’S USE.
THIS MEANS OFTEN MORE THAN ONE WORD IS USED AS AN
IDENTIFIER.
 THE FORMATTING CONVENTION USED HERE IS KNOWN AS
CAMELCAPS. IT MAKES AN IDENTIFIER EASIER TO READ.
 IDENTIFIER NAME SHOULD NOT BE ANY KEYWORD LIKE IF, ELSE OR
FOR.
Topic Chapter 12
Variable Assignment Algorithm Design and Problem Solving

12.05 Assignments
Assigning a value:
The following pseudocode stores the value to an identifier
Number
(See Figure 12.05(a)).
The following pseudocode stores the value 1 in the variable
with the identifier NumberOfGuesses (see Figure
12.05(b)).

NumberOfGuesses  1
Topic Chapter 12
Updating a value Algorithm Design and Problem Solving

• The following pseudocode takes the


value stored in NUMBEROFGUESSES
(see figure 12.06 (a)), adds 1 to that
value and then stores the new value
back into the variable
NUMBEROFGUESSES (see figure
12.06 (b)).
• NUMBEROFGUESSES 
NUMBEROFGUESSES + 1
Topic Chapter 12
Updating a value Algorithm Design and Problem Solving

• UPDATING A VALUE
count count +
count 0
1

0 1

count count

(a (b
) )
Topic Chapter 12
Algorithm Design and Problem Solving
Copying a value

• COPYING A VALUE

Value2 Value1

15

(a Value1 Value2
)

15 15

(b Value1 Value2
)
Topic Chapter 12
Swapping two values Algorithm Design and Problem Solving

• SWAPPING TWO VALUES

Pseudocode of
Swapping:

Temp  Value1

Value1  Value2

Value2  Temp
ITERATION
ITERATION

• WHAT IF WE NEED TO TELL THE COMPUTER TO KEEP DOING SOMETHING


UNTIL SOME CONDITION OCCURS ?
ITERATION

• WHAT IF WE NEED TO TELL THE COMPUTER TO KEEP DOING SOMETHING


UNTIL SOME CONDITION OCCURS ?
• LET’S SAY WE WISH TO INDICATE THAT ONE NEED TO KEEP FILLING THE
KETTLE WITH WATER UNTIL IT IS FULL.
ITERATION

• WHAT IF WE NEED TO TELL THE COMPUTER TO KEEP DOING SOMETHING


UNTIL SOME CONDITION OCCURS ?
• LET’S SAY WE WISH TO INDICATE THAT THE YOU NEED TO KEEP FILLING THE
KETTLE WITH WATER UNTIL IT IS FULL.
• WE NEED A LOOP, OR ITERATION.
TYPES OF ITERATION

Iteration

Count Condition
Controlled loop Controlled loop
Example: For… Pre- Post-
Next condition condition
Ex: While..End Ex: Repeat
While …..Until
ITERATION

• SYNTAX OF WRITING ITERATION IN PSEUDOCODE IS AS FOLLOWS:

WHILE (<CONDITION>)
DO <STATEMENTS>
ENDWHILE
ITERATION

 SO, WE COULD STATE THIS AS:

WHILE (KETTLE IS NOT FULL)


DO KEEP FILLING KETTLE
ENDWHILE
ITERATION
Write pseudocode to print
numbers from 1 to 5:
(Using Count-Controlled Loop)

DECLARE count: INTEGER


FOR count  1 TO 5
PRINT count
NEXT count
ITERATION

 Write pseudocode to print numbers


from
11 to 15. (Using Count - Controlled
Loop)
FOR count  11 TO 15
PRINT count
NEXT count
ITERATION

 Write pseudocode to print numbers


from
11 to 15. (Using Condition-Controlled
Loop)
ITERATION
 Write pseudocode to print numbers from 11
to 15 (using Condition control loop):
 WHILE...ENDWHI  REPEAT ...UNTIL
LE
count  11 count  11
WHILE(count <= 15) REPEAT
PRINT count
PRINT count
count  count + 1
count  count + 1 UNTIL(count > 15)OR
ENDWHILE UNTIL(count = 16)
ITERATION
• WRITE PSEUDOCODE TO ADD CONSECUTIVE
NUMBERS FROM1 TO 100 AND PRINT THE
RESULT (USING COUNT CONTROLLED LOOP)
PSEUDOCODE
 Add consecutive numbers from 1 to 100
and print out the result (using Count-
controlled Loop)

TOTAL  0
FOR Num  1 TO 100
TOTAL  TOTAL + Num
NEXT Num
PRINT TOTAL
PSEUDOCODE
Add up the numbers from 1 to 100 and print
out the result (using Condition-controlled
Loop)
PSEUDOCODE
Add up the numbers 1 to 100 and print out
the result (using Condition-controlled Loop)

TOTAL  0
Num  1
WHILE (Num<=100)/(Num<101)/(Num<>101)
TOTAL  TOTAL + Num

Num  Num + 1

ENDWHILE
PRINT TOTAL
PSEUDOCODE
Add up the numbers 1 to 100 and print out
the result (using Condition-controlled Loop)

TOTAL  0
A  1
REPEAT
TOTAL  TOTAL + A
A  A + 1
UNTIL (A > 100) / UNTIL (A = 101)
PRINT TOTAL
PSEUDOCODE
Working 1: Write a pseudocode to calculate and
print the sum of the following series using three
different loop structures.

1+2+3+4+…….+100 =?
WHILE..ENDWHILE
FOR…ENDFOR REPEAT….UNTIL Loop
Loop Loop
PSEUDOCODE
Working 1: Write a pseudocode to calculate and
print the sum of the following series using three
different loop structures.

1+2+3+4+…….+100 = ?
FOR…NEXT WHILE..END WHILE REPEAT….UNTIL
Loop Loop Loop

Total  0 Total 0 Total 0


count 1 Count 1
FOR count1 TO 100 REPEAT
WHILE(count<=100)
TotalTotal+count TotalTotal+count TotalTotal+count
countcount+1
NEXT count countcount+1
UNTIL(count>100)
ENDWHILE
PRINT Total PRINT Total
PRINT Total
PSEUDOCODE
 Homework:

Working 2: Write a pseudocode to calculate and


print the sum of the following series using three
different loop structures.

0+2+4+6+…….+100 = ?

 Instructions:
 Homework is given on LMS as assignment
 Do it in your school copy
 Take picture and convert it into pdf file
 Attach the file as an attachment on LMS
WORKING 5:(O-LEVEL JUNE 2004)
1. USING PSEUDOCODE, OR OTHERWISE, WRITE AN ALGORITHM THAT WILL
INPUT THE HOURLY TEMPERATURES FOR ONE DAY IN CENTIGRADE AND PRINT
OUT IN FAHRENHEIT.
• THE MAXIMUM TEMPERATURE
• THE MINIMUM TEMPERATURE
• THE AVERAGE TEMPERATURE FOR THAT DAY.

FORMULA: F  (C * 1.8) + 32
SOLUTION(USING THREE DIFFERENT
LOOPS):
FOR……NEXT WHILE…… END REPEAT ……UNTIL
WHILE
SOLUTION(USING THREE DIFFERENT
LOOPS):
FOR……NEXT WHILE…… END WHILE REPEAT ……UNTIL
total  0 total  0 total  0
min  100 min  100 min  100
max  -100 max  -100 max  -100
FOR count  1 TO 24 count  1 count  1
INPUT temp WHILE count <= 24 REPEAT
F  (temp * 1.8) + 32 INPUT temp INPUT temp
total  total + F F  (temp * 1.8) + 32 F  (temp * 1.8) + 32
IF F < min THEN min  total  total + F total  total + F
F IF F < min THEN min  IF F < min THEN min 
IF F > max THEN max F F
F IF F > max THEN max IF F > max THEN max 
ENDFOR F F
average  total /24 count  count + 1 count  count + 1
PRINT average, min, ENDWHILE UNTIL count > 24
max average  total/24 average  total/24
PRINT average, min, PRINT average, min, max
max
Topic Chapter 12
Worked example 12.01 Algorithm Design and Problem Solving
Topic Chapter 12
Worked example 12.01 Algorithm Design and Problem Solving
Topic Chapter 12
Task 12.03 Algorithm Design and Problem Solving

 Flow chart :
Topic Chapter 12
Task 12.06 Algorithm Design and Problem Solving

 A person is classed as a child if they are under 13 and as an adult


if they are over 19. If they are between 13 and 19 inclusive they are
classed as teenagers. We can write these statements as logic
statements.
Topic Chapter 12
Task 12.06 Algorithm Design and Problem Solving

• The selection construct in Table 12.01 uses a condition to follow either the
first group of steps or the second group of steps (see Figure 12.10).
• condition consists of at least one logic proposition. Logic propositions use
the relational (comparison) operators shown in Table 12.03.

Conditions are either TRUE or FALSE. In pseudocode, we distinguish between the relational
operator =
(which tests for equality) and the assignment symbol ←.
Topic Chapter 12
Algorithm Design and Problem
Nested If Solving

 NESTED IF :

• WHEN AN IF STATEMENT CONTAINS ANOTHER IF STATEMENT , WE REFER TO


AS NESTED IF.
Topic Chapter 12
Algorithm Design and Problem
Selection Construct (Worked example: 12.02) Solving

 THE PROBLEM TO BE SOLVED(USING NESTED IF STATEMENT):

TAKE THREE NUMBERS AS INPUT AND OUTPUT THE LARGEST


NUMBER.
THERE ARE SEVERAL DIFFERENT METHODS (ALGORITHMS)
TO SOLVE THIS PROBLEM.
HERE IS ONE METHOD:
1. INPUT ALL THREE NUMBERS AT THE BEGINNING.
2. STORE EACH OF THE INPUT VALUES IN A SEPARATE VARIABLE.
3. COMPARE THE FIRST NUMBER WITH THE SECOND NUMBER AND THEN
COMPARE THE BIGGER ONE OF THESE WITH THE THIRD NUMBER.
4. THE BIGGER NUMBER OF THIS SECOND COMPARISON IS OUTPUT.
Topic Chapter 12
Selection Construct Algorithm Design and Problem Solving
Topic Chapter 12
Algorithm Design and Problem Solving
Selection Construct
Chapter 12
Topic Algorithm Design and Problem
Selection Construct Solving
Topic Chapter 12
Algorithm Design and Problem Solving
Selection Construct

• USING SELECTION CONSTRUCTS(ALTERNATIVE METHOD)


Topic Chapter 12
Algorithm Design and Problem Solving
Selection Constructs

THERE ARE SEVERAL ADVANTAGES OF USING THE


METHOD IN WORKED EXAMPLE 12.03 COMPARED
TO THE METHOD IN WORKED EXAMPLE 12.02:
• ONLY TWO VARIABLES ARE USED.
• THE CONDITIONAL STATEMENTS ARE NOT NESTED
AND DO NOT HAVE AN ELSE PART.
• THIS MAKES THEM EASIER TO UNDERSTAND.
• THIS ALGORITHM CAN BE ADAPTED MORE EASILY IF
FURTHER NUMBERS ARE TO BE COMPARED.
Topic Chapter 12
Algorithm Design and Problem Solving
Selection Constructs

• THE DISADVANTAGE OF THE METHOD IN WORKED EXAMPLE


12.03 COMPARED TO THE METHOD IN WORKED EXAMPLE
12.02 IS THAT THERE IS MORE WORK INVOLVED WITH THIS
ALGORITHM.
• IF THE SECOND NUMBER IS BIGGER THAN THE FIRST
NUMBER, THE VALUE OF BIGGESTSOFAR HAS TO BE CHANGED.
• IF THE THIRD NUMBER IS BIGGER THAN THE VALUE IN
BIGGESTSOFAR, THEN AGAIN THE VALUE OF BIGGESTSOFAR
HAS TO BE CHANGED.
• TO COMPARE 10 NUMBERS WE WOULD NEED TO WRITE
COMPARATIVE STATEMENTS AMONG TWO VARIABLES
BIGGESTSOFAR AND NEXTNUMBER WILL NEED TO WRITE NINE
TIMES.
Chapter 12
Topic Algorithm Design and Problem
Iteration/Loops/Repetition Solving

 WORKED EXAMPLE 12.05

 MOREOVER, IF THE PROBLEM CHANGED TO HAVING


TO COMPARE, FOR EXAMPLE, 100 NUMBERS, OUR
ALGORITHM WOULD BECOME VERY TEDIOUS.
 LF WE USE A REPETITION CONSTRUCT (A LOOP) WE
CAN AVOID WRITING THE SAME LINES OF
PSEUDOCODE OVER AND OVER AGAIN.
Chapter 12
Topic Algorithm Design and Problem Solving
Iteration/Loops/Repetition

 WORKED EXAMPLE 12.05:

• REPETITION USING REPEAT….UNTIL

THE PROBLEM CAN BE SOLVED USING ITERATION IN PLACE OF SELECTION:


TAKE 10 NUMBERS AS INPUT AND OUTPUT THE LARGEST NUMBER.
Topic Chapter 12
Algorithm Design and Problem Solving
Iteration/Loops/Repetition

• REPETITION USING FOR….END FOR

THE PROBLEM TO BE SOLVED:


TAKE 10 NUMBERS AS INPUT AND OUTPUT THE LARGEST NUMBER.

The first time round the loop, counter is set to 2, the next time
round the loop. Counter has automatically increases to 3, and so
on. The last time round the loop, counter has value 10.
Chapter 12
Topic Algorithm Design and Problem
Iteration/Loops/Repetition Solving

• REPETITION USING A ROGUE VALUE:

• A rogue value is a value used to terminate a sequence of


values. The rogue value is of the same data type but
outside the range of normal expected values.

• It is used to terminate a loop, basically it is point of


termination.
• If the data type is of Integer it can be a number like 0 or
999 and if the data type is a string , the rogue value can be
“End”.
Topic Chapter 12
Algorithm Design and Problem Solving
Iteration/Loops/Repetition

• REPETITION USING A ROGUE VALUE:


Topic Chapter 12
Algorithm Design and Problem Solving
Iteration/Loops/Repetition

• REPETITION USING A ROGUE VALUE (WHILE…ENDWHILE):


Topic Chapter 12
Iteration/Loops/Repetition Algorithm Design and Problem Solving
Topic Chapter 12
Iteration/Loops/Repetition Algorithm Design and Problem Solving

• THE ALGORITHM IS EXPRESSED IN STRUCTURED ENGLISH, AS A


FLOWCHART AND IN PSEUDOCODE.
• ALGORITHM FOR THE NUMBER-GUESSING GAME IN STRUCTURED
ENGLISH.
• SET VALUE FOR SECRET NUMBER
• REPEAT THE FOLLOWING UNTIL CORRECT GUESS
• INPUT GUESS
• COMPARE GUESS WITH SECRET NUMBER
• OUTPUT COMMENT
• WE NEED VARIABLES TO STORE THE FOLLOWING VALUES:
 THE SECRET NUMBER (TO BE SET AS A RANDOM NUMBER)
 THE NUMBER INPUT BY THE PLAYER AS A GUESS
 THE COUNT OF HOW MANY GUESSES THE PLAYER HAS MADE SO FAR
Topic Chapter 12
Algorithm Design and Problem
Identifier Table Solving

 We need variables to store the following values:


 the secret number (to be set as a random number)
 the number input by the player as a guess
 the count of how many guesses the player has made so far.
Topic Chapter 12
Number guessing problem Algorithm Design and Problem Solving
Topic Chapter 12
Algorithm Design and Problem
Number guessing problem Solving
Topic Chapter 12
Algorithm Design and Problem
Number guessing problem Solving
Topic Chapter 12
Algorithm Design and Problem
Number guessing problem Solving

• CHANGE THE PREVIOUS ALGORITHM SO THAT THE


USER CAN ONLY MAKE 10 GUESSES.
Topic Chapter 12
Algorithm Design and Problem
Number guessing problem Solving

• MODIFY THE PREVIOUS ALGORITHM SO THAT THE USER


CAN QUIT THE GAME BY INPUTTING ZERO AS A ROGUE
VALUE.
Topic Chapter 12
Algorithm Design and Problem
Worked Example 12.08 Solving
Topic Chapter 12
Algorithm Design and Problem
Worked example 12.09: Solving

 Worked example 12.09: Take rows, columns and a symbol as


input.
Output a grid made up entirely of the chosen symbol, with the
number of rows and the number of columns given by the user.
Topic Chapter 12
Algorithm Design and Problem
Worked Example 12.08 Solving

Pseudocode :

INPUT NumberOfRows
INPUT NumberOfColumns
INPUT Symbol
FOR RowCounter  1 TO NumberOfRows
FOR ColumnCounter  1 TO NumberOfColumns
OUTPUT Symbol // Without moving to next line
NEXT ColumnCounter
OUTPUT Newline // move to the next line
NEXT RowCounter
Topic Chapter 12
Algorithm Design and Problem Solving
Worked example 12.09:

 Worked example 12.09: Take rows, columns and a symbol as


input.
Output a grid made up entirely of the chosen symbol, with the
number of rows and the number of columns given by the user.
Program code for 12.09 :
rows =int(input("Please enter how many rows?"))
columns =int(input("Please enter how many columns?"))
symbol= input("Please enter any symbol: ")
for i in range(0, rows):
for j in range (0, columns):
print (symbol, end= '')
print('\n')
CHAPTER -12
ALGORITHM DESIGN AND PROBLEM SOLVING

Top-down design of a
solution
• As problems solved by computer
programs have become bigger and
more complex, it has become difficult
for one person to devise a solution or
to implement it on their own.
• A Modular, top-down design can
handle such problems.
TOPIC:
CHAPTER -12
STEPWISE REFINEMENT ALGORITHM
DESIGN AND PROBLEM SOLVING

• In a modular top down design, the whole task


split into smaller subtasks to solve the
complexity of a bigger and difficult computer
program.
• These subtasks are then repeatedly split into
even smaller subtasks.
• Eventually each task becomes so small that
it can easily be programmed.
• The program for each subtask can then be
implemented independently as a separate
module, and then the modules can be put
together to create a solution for the main
problem.
TOPIC:
CHAPTER -12
STEPWISE REFINEMENT ALGORITHM DESIGN AND
PROBLEM SOLVING
12.08 Stepwise refinement
Topic:
Chapter -12
Stepwise Refinement for pay calculation Algorithm
Design and Problem Solving

Calculate Wages

INPUT Hours
CALCULATE OUTPUT
INPUT Rate of
Take home pay Pay details
pay

CALCULAT
CALCULATE OUTPUT Pay ,
E CALCULATE
Tax and Hours, Total
Hours * Pay-Tax-
other Pay , Tax , Other
Rate of Deduction
deduction Deduction , Take
pay
home Pay
TOPIC: CHAPTER -12
STEPWISE REFINEMENT ALGORITHM DESIGN AND PROBLEM SOLVING

• WORKED EXAMPLE 12.10


Drawing a pyramid using stepwise refinement
The problem to be solved: Take as input a chosen symbol and an odd
number. Output a pyramid shape made up entirely of the chosen
symbol, with the number of symbols in the final row matching the
number input.
For example the two input values A and 9 result in the following
output:
A
AAA
AAAAA
AAAAAAA
AAAAAAAAA
This problem is similar to Worked Example 12.09, but the number of
symbols in each row starts with one and increases by two with each
row. Each row starts with a decreasing number of spaces, to create
the slope effect.

Our first attempt at solving this problem using structured English is:
01 Set up initial values
02 REPEAT
03 Output number of spaces
04 Output number of symbols
TOPIC: CHAPTER -12
STEPWISE REFINEMENT ALGORITHM DESIGN AND PROBLEM SOLVING

 Exactly what values do we need to set?


We need as input:
the symbol character from which the pyramid is to be formed the
number of symbols in the final row (for the pyramid to look
symmetrical, this needs to be an odd number).
We need to calculate how many spaces we need in the first row. So
that the slope of the pyramid is symmetrical, this number should be
half of the final row’s symbols. We need to set the number of symbols
to be output in the first row to 1.
We therefore need the identifiers listed in Table 12.12.
TOPIC:
CHAPTER -12
STEPWISE REFINEMENT ALGORITHM DESIGN AND
PROBLEM SOLVING

• Using pseudocode, we now refine the steps of our first attempt. To


show which step we are refining, a numbering system is used as
shown.

Step 01 can be broken down as follows:
01 // Set up initial values expands into:
01.1 INPUT Symbol
01.2 INPUT MaxNumberOfSymbols
01.3 NumberOfSpaces ← (MaxNumberOfSymbols – 1) / 2
01.4 NumberOfSymbols ← 1

Remember we need an odd number for MaxNumberOfSymbols. We
need to make sure the input is an odd number.
TOPIC:
CHAPTER -12
STEPWISE REFINEMENT ALGORITHM DESIGN
AND PROBLEM SOLVING

• So we further refine Step 01.2:



01.2 // INPUT MaxNumberOfSymbols expands into:
01.2.1 REPEAT
01.2.2 INPUT MaxNumberOfSymbols
01.2.3 UNTIL MaxNumberOfSymbols MOD 2 = 1
01.2.4 // MOD 2 gives the remainder after integer division
by 2

We can now look to refine Steps 03 and 04:
03 // Output number of spaces expands into:
03.1 FOR i ← 1 TO NumberOfSpaces
03.2 OUTPUT Space // without moving to next line
03.3 NEXT i
04 // Output number of symbols expands into:
04.1 FOR i ← 1 TO NumberOfSymbols
04.2 OUTPUT Symbol // without moving to next line
04.3 NEXT i
04.4 OUTPUT Newline // move to the next line
TOPIC:
CHAPTER -12
STEPWISE REFINEMENT ALGORITHM DESIGN
AND PROBLEM SOLVING

• In Step 05 we need to decrease the number of spaces by 1 and


increase the number of symbols by 2:
05 // Adjust values for next row expands into:
05.1 NumberOfSpaces ← NumberOfSpaces – 1
05.2 NumberOfSymbols ← NumberOfSymbols + 2

Step 06 essentially checks whether the number of symbols for the
next row is now greater than the value input at the beginning.
06 UNTIL NumberOfSymbols > MaxNumberOfSymbols
We can put together all the steps and end up with a solution.
01 // Set Values
01.1 INPUT Symbol
01.2 // Input max number of symbols (an odd number)
01.2.1 REPEAT
01.2.2 INPUT MaxNumberOfSymbols
01.2.3 UNTIL MaxNumberOfSymbols MOD 2 = 1
01.3 NumberOfSpaces ← (MaxNumberOfSymbols – 1) / 2
01.4 NumberOfSymbols ← 1
TOPIC:
CHAPTER -12
STEPWISE REFINEMENT ALGORITHM DESIGN
AND PROBLEM SOLVING

• 02 REPEAT
03 // Output number of spaces
03.1 FOR i ← 1 TO NumberOfSpaces
03.2 OUTPUT Space // without moving to next line
03.3 NEXT i
04 // Output number of symbols
04.1 FOR i ← 1 TO NumberOfSymbols
04.2 OUTPUT Symbol // without moving to next line
04.3 NEXT i
04.4 OUTPUT Newline // move to the next line
05 // Adjust Values For Next Row
05.1 NumberOfSpaces ← NumberOfSpaces – 1
05.2 NumberOfSymbols ← NumberOfSymbols + 2
06 UNTIL NumberOfSymbols > MaxNumberOfSymbols
TOPIC: CHAPTER -12
STEPWISE REFINEMENT ALGORITHM DESIGN AND PROBLEM
SOLVING

• Drawing a pyramid using modules



The problem is the same as in Worked Example 12.10.
When we want to set up the initial values, we call a procedure, using
the following statement:
CALL SetValues
We can rewrite the top-level solution to our pyramid problem using a
procedure for each step, as:
CALL SetValues
REPEAT
CALL OutputSpaces
CALL OutputSymbols
CALL AdjustValuesForNextRow
UNTIL NumberOfSymbols > MaxNumberOfSymbols
• This top-level solution calls four procedures. This means each
procedure has to be defined.
TOPIC:
CHAPTER -12
STEPWISE REFINEMENT ALGORITHM DESIGN
AND PROBLEM SOLVING

 Procedure definitions are:

PROCEDURE SetValues
INPUT Symbol
CALL InputMaxNumberOfSymbols // need to
ensure it is an odd number
NumberOfSpaces ← (MaxNumberOfSymbols - 1) /
2
NumberOfSymbols ← 1
ENDPROCEDURE

PROCEDURE InputMaxNumberOfSymbols
REPEAT
INPUT MaxNumberOfSymbols
UNTIL MaxNumberOfSymbols MOD 2 = 1
ENDPROCEDURE
TOPIC:
CHAPTER -12
STEPWISE REFINEMENT ALGORITHM DESIGN
AND PROBLEM SOLVING

PROCEDURE OutputSpaces
FOR Count1 ← 1 TO NumberOfSpaces
OUTPUT Space // without moving to next line
NEXT Count1
ENDPROCEDURE

PROCEDURE OutputSymbols
FOR Count2 ← 1 TO NumberOfSymbols
OUTPUT Symbol // without moving to next line
NEXT Count2
OUTPUT Newline // move to the next line
ENDPROCEDURE

PROCEDURE AdjustValuesForNextRow
NumberOfSpaces ← NumberOfSpaces – 1
NumberOfSymbols ← NumberOfSymbols + 2
ENDPROCEDURE
Topic:
Chapter -12
Advantage of Top-Down Design Algorithm
Design and Problem Solving

ADVANTAGES OF TOP-DOWN DESIGN OF A


SOLUTION
1. THE PROGRAM IS EASIER TO WRITE AND TEST.
2. EACH MODULE IS SMALL AND CAN BE WRITTEN AND TESTED
INDEPENDENTLY.
3. THE PROGRAM DESIGN CLEARLY SHOWS HOW THE DIFFERENT PARTS
OF A LARGE PROGRAM RELATE TO EACH OTHER.
4. THIS REDUCES ERRORS CAUSED BY DIFFERENT PARTS OF A LARGE
PROGRAM INTERFERING WITH EACH OTHER.
5. WORKING ON SEPARATE MODULES, THE PROGRAM CAN DEVELOP
EASILY BY A TEAM OF PROGRAMMERS.
6. THE MODULES CAN BE ALLOCATED ACCORDING TO THE EXPERTISE
OF EACH PROGRAMMER.
7. THE MODULES ARE WRITTEN SEPARATELY TO PERFORM A SMALL,
SPECIFIC TASK, AND THEY CAN BE REUSED IN OTHER PARTS OF THE
PROGRAMS OR OTHER PROGRAMS WHENEVER THAT TASK NEEDS.

You might also like