0% found this document useful (0 votes)
13 views

CH12伪代码

Uploaded by

Luz J
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

CH12伪代码

Uploaded by

Luz J
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

CH.

12 Algorithm design & problem-solving


12.1 Expressing algorithms
Structured English Pseudocode Flowchart

Assignme SET A TO 34 A 34
nt & INCREMENT B B B+1
Sequence

Selection IF A IS GREATER IF A>B


THAN B THEN…
THEN… ELSE…
ELSE… ENDIF

Repetitio REPEAT UNTIL A IS REPEAT


n EQUAL TO B… …
UNTIL A=B

Input INPUT A INPUT “Prompt:”A

Output OUTPUT “Message” OUTPUT “Message”,B


OUTPUT B

12.2 Assignments
12.2.1 Assigning a value
stores the value that is input in a variable with the identifier Number

INPUT Number

stores the value 1 in the variable with the identifier NumberOfGuesses

NumberOfGuesses ← 1

12.2.2 Updating a value

The following pseudocode takes the value stored in NumberOfGuesses adds 1 to that value and then stores
the new value back into the variable NumberOfGuesses

NumberOfGuesses ← NumberOfGuesses + 1

12.2.3 Copying a value

Values can be copied from one variable to another. The following pseudocode takes the value stored in
Value1 and copies it to Value2

Value2 ← Value1

The value in Value1 remains the same until it is assigned a different value.

12.2.4 Swapping two values

Temp  Value1

Value1  Value2

Value2  Temp

Worked Example 12.01

Using input, output, assignment and sequence constructs

The problem to be solved: Convert a distance in miles and output the equivalent distance in km.

Solution:

INPUT “Enter miles:” Miles

Km  Miles*1.61

OUTPUT “km:”,km
12.3 Logic Statements

Pseudocode for the selection construct

IF A < B

THEN

<statement(s)>

ELSE

<statement(s)>

ENDIF

Operator Comparison
= Is equal to
< Is less than
> Is greater than
<= Is less than or equal to
>= Is greater than or equal to
<> Is not equal to

Conditions are either TRUE or FALSE. In pseudocode, we distinguish between the relational operator = (which
tests for equality) and the assignment symbol .

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.

 If Age < 13 then person is a child.


 If Age > 19 then person is an adult.
 If Age >= 13 AND Age <= 19 then person is a teenager.

A number-guessing game follows different steps depending on certain conditions. Here is a description of the
algorithm.

 The player inputs a number to guess the secret number stored.


 If the guess was correct, output a congratulations message.
 If the number input was larger than the secret number, output message “secret number is smaller”.
 If the number input was smaller than the secret number, output message “secret number is greater”.

We can re-write the number-guessing game steps as an algorithm in pseudocode:

SET value for the secret number

INPUT Guess

IF Guess = SecretNumber
THEN

OUTPUT “Well done. You have guessed the secret number”

ELSE

IF Guess > SecretNumber

THEN

OUTPUT “Secret number is smaller.”

ELSE

OUTPUT “Secret number is larger.”

ENDIF

ENDIF

the number-guessing game might allow the player multiple guesses; if the player has not guessed the secret
number after 10 guesses, a different message is output.

IF Guess = SecretNumber

THEN

OUTPUT “Well done. You have guessed the secret number”

ELSE

IF Guess <> SecretNumber AND NumberofGuesses = 10

THEN

OUTPUT “You still have not guessed the secret number”

ELSE

IF Guess > SecretNumber

THEN

OUTPUT “Secret number is smaller”

ELSE

OUTPUT “Secret number is larger”

ENDIF
ENDIF

ENDIF

Worked Example 12.02

Using selection constructs

The problem to be solved: 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 (the identifiers are shown in Table 12.04).

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.

INPUT Number1

INPUT Number2

INPUT Number3

IF Number1 > Number2 //Number1 is larger

THEN

IF Number1 > Number3 //Number1 is the largest

THEN

OUTPUT Number1

ELSE

OUTPUT Number3

ENDIF

ELSE //Number2 is larger

IF number2 > number3 //Number2 is the largest

THEN

OUTPUT Number2
ELSE //Number3 is the largest

OUTPUT Number3

ENDIF

ENDIF

Worked Example 12.03

Using selection constructs (alternative method)

The problem to be solved: Take three numbers as input and output the largest number.

This is an alternative method to Worked Example 12.02.

1 Input the first number and store it in BiggestSoFar

2 Input the second number and compare it with the value in BiggestSoFar.

3 If the second number is bigger, assign its value to BiggestSoFar

4 Input the third number and compare it with the value in BiggestSoFar

5 If the third number is bigger, assign its value to BiggestSoFar

6 The value stored in BiggestSoFar is output.

INPUT BiggestSoFar

INPUT NextNumber

IF NextNumber > BiggestSoFar

THEN

BiggestSoFar NextNumber

ENDIF

INPUT NextNumber

IF NextNumber > BiggestSoFar

THEN

BiggestSoFar NextNumber

ENDIF

OUTPUT BiggestSoFar
12.4 Loops

Worked Example 12.04

Repetition using REPEAT...UNTIL

The problem to be solved: Take 10 numbers as input and output the largest number.
We need one further variable to store a counter, so that we know when we have compared 10 numbers.

INPUT BiggestSoFar

Counter  1 // Stores how many numbers have been input so far

REPEAT

INPUT NextNumber

Counter  Counter + 1

IF NextNumber > BiggestSoFar

THEN

BiggestSoFar  NextNumber

ENDIF

UNTIL Counter = 10

OUTPUT BiggestSoFar

Worked Example 12.05

Repetition using FOR...NEXT

The problem to be solved: Take 10 numbers as input and output the largest number.
We can use the same identifiers as in Worked Example 12.04. Note that the purpose of Counter has changed.

INPUT BiggestSoFar

FOR Counter  2 TO 10 // Counts the number of times round the loop

INPUT NextNumber

IF NextNumber > BiggestSoFar

THEN

BiggestSoFar  NextNumber

ENDIF
NEXT Counter

OUTPUT BiggestSoFar

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.

Worked Example 12.06

Repetition using a rogue value

The problem to be solved: A sequence of non-zero numbers is terminated by 0. Take this sequence as input and
output the largest number.

Note: In this example the rogue value chosen is 0. It is very important to choose a rogue value that is of the same
data type but outside the range of normal expected values. For example, if the input might normally include 0
then a negative value, such as −1, might be chosen.

Look at Worked Example 12.05. Instead of counting the numbers input, we need to check whether the number
input is 0 to terminate the loop.

INPUT BiggestSoFar

REPEAT

INPUT NextNumber

IF NextNumber > BiggestSoFar

THEN

BiggestSoFar NextNumber

ENDIF

UNTIL NextNumber = 10

OUTPUT BiggestSoFar

This algorithm works even if the sequence consists of only one non-zero input. However, it will not work if the only
input is 0. In that case, we don’t want to perform the statements within the loop at all. We can use an alternative
construct, the WHILE...ENDWHILE loop.

INPUT NextNumber

BiggestSoFar  NextNumber

WHILE NextNumber <> 0 DO //run the following until NextNumber=0

INPUT NextNumber
IF NextNumber > BiggestSoFar

THEN

BiggestSoFar NextNumber

ENDIF

ENDWHILE

OUTPUT BiggestSoFar

Before we enter the loop, we check whether we have a non-zero number. To make this work for the first number,
we store it in NextNumber and also in BiggestSoFar. If this first number is zero, we don’t follow the instructions
within the loop. For a non-zero first number this algorithm has the same effect as the algorithm using
REPEAT...UNTIL.

Worked Example 12.07

Implementing the number-guessing game with a loop

Consider the number-guessing game again, this time allowing repeated guesses.

1 The player repeatedly inputs a number to guess the secret number stored.

2 If the guess is correct, the number of guesses made is output and the game stops.

3 If the number input is larger than the secret number, the player is given the message

to input a smaller number.

4 If the number input is smaller than the secret number, the player is given the message to input a larger
number.

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.

Pseudocode for the number-guessing game with a post-condition loop

SecretNumber  Random

NumberOfGuesses  0

REPEAT

INPUT Guess

NumberOfGuesses  NumberOfGuesses + 1
IF Guess > SecretNumber

THEN

OUTPUT “Too large”

ENDIF

IF Guess < SecretNumber

THEN

OUTPUT “Too Small”

ENDIF

UNTIL Guess = SecretNumber

OUTPUT NumberOfGuesses

Pseudocode for the number-guessing game with a pre-condition loop

SecretNumber  Random

INPUT Guess

NumberOfGuesses  1

WHILE Guess <> SecretNumber DO

IF Guess > SecretNumber

THEN

OUTPUT “Too large”

ENDIF

IF Guess < SecretNumber

THEN

OUTPUT “Too Small”

ENDIF

INPUT Guess

NumberOfGuesses  NumberOfGuesses + 1

ENDWHILE
OUTPUT NumberOfGuesses

Worked Example 12.08

Calculating running totals and averages

The problem to be solved: Take 10 numbers as input and output the sum of these numbers and the average.

Sum1  0. //Sum1 is initialised to zero before we start adding the numbers being input.

FOR i  1 TO 10 // i as number of inputs

INPUT NextNumber

Sum1  Sum1 + NextNumber

NEXT i

OUTPUT Sum1 //sum of the 10 numbers inputted

Average  Sum1 / 10

OUTPUT Average //average of those numbers

Worked Example 12.09

Using nested loops

The problem to be solved: Take as input two numbers and a symbol. Output a grid made up entirely of the chosen
symbol, with the number of rows matching the first number input and the number of columns matching the
second number input.
For example the three input values 3, 7 and &, result in the output:

&&&&&&&

&&&&&&&

&&&&&&&

We need two variables to store the number of rows and the number of columns. We also need a variable to store
the symbol. We need a counter for the rows and a counter for the columns.

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

Each time round the outer loop (counting the number of rows) we complete the inner loop, outputting a symbol
for each count of the number of columns. This type of construct is called a nested loop.

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:

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.

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.

// Set Values

INPUT Symbol

// Input max number of symbols (an odd number)

REPEAT
INPUT MaxNumberOfSymbols

UNTIL MaxNumberOfSymbols MOD 2 = 1 //对 2 取余

NumberOfSpaces  (MaxNumberOfSymbols-1)/2

NumberOfSymbols  1

REPEAT

// Output number of spaces

FOR i  1 TO NumberOfSpaces

OUTPUT Space // without moving to next line

NEXT i

// Output number of symbols

FOR i  1 TO NumberOfSymbols

OUTPUT Symbol // without moving to next line

NEXT i

OUTPUT Newline // move to the next line

// Adjust Values For Next Row

NumberOfSpaces  NumberOfSpaces-1

NumberOfSymbols  NumberOfSymbols+2

UNTIL NumberOfSymbols > MaxNumberOfSymbols

12.5 Modules

Another method of developing a solution is to decompose the problem into sub-tasks. Each sub-task can be
considered as a ‘module’ that is refined separately. Modules are procedures and functions.

Procedure: a sequence of steps that is given an identifier and can be called to perform a sub-task
Function: a sequence of steps that is given an identifier and returns a single value; function call is part of an expression

Note: Because a function returns a value, the function definition states the data type of this value.

The rules for module identifiers are the same as for variable identifiers

Worked Example 12.11

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. The 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

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

Worked Example 12.12

Drawing a pyramid using modules

The problem is the same as in Worked Example 12.11.


We can rewrite the top-level solution to our pyramid problem using procedures and functions.

01 CALL SetValues

02 REPEAT

03 CALL OutputSpaces
04 CALL OutputSymbols

05.1 NumberOfSpaces ← AdjustedNumberOfSpaces

05.2 NumberOfSymbols ← AdjustedNumbeOfSymbols

06 UNTIL NumberOfSymbols > MaxNumberOfSymbols

This top-level solution calls three procedures. It also makes use of two functions in lines 05.1 and 05.2.

The procedures and functions have to be defined.

PROCEDURE SetValues

INPUT Symbol

MaxNumberOfSymbols ← ValidatedMaxNumberOfSymbols

NumberOfSpaces ← (MaxNumberOfSymbols - 1) / 2

NumberOfSymbols ← 1

ENDPROCEDURE

FUNCTION ValidatedMaxNumberOfSymbols RETURNS INTEGER

REPEAT

INPUT MaxNumberOfSymbols

UNTIL MaxNumberOfSymbols MOD 2 = 1

RETURN MaxNumberOfSymbols

ENDFUNCTION

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

FUNCTION AdjustedNumberOfSpaces RETURNS INTEGER

NumberOfSpaces ← NumberOfSpaces – 1

RETURN NumberOfSpaces

ENDFUNCTION

FUNCTION AdjustedNumberOfSymbols RETURNS INTEGER

NumberOfSymbols ← NumberOfSymbols + 2
RETURN NumberOfSymbols

ENDFUNCTION

Note that procedure SetValues uses a function ValidatedMaxNumberOfSymbols

One benefit of using modules is that individual modules can be reused in other solutions. Therefore, modules
should be designed to be self-contained. That means they should not rely on external variables. All variables that
are required by a module should be passed to it using parameters.

Worked Example 12.13

Drawing a pyramid using modules and parameters

The problem is the same as in Worked Example 12.12.

01 CALL SetValues(Symbol, MaxNumberOfSymbols, NumberOfSpaces, NumberOfSymbols)

02 REPEAT

03 CALL OutputSpaces(NumberOfSpaces)

04 CALL OutputSymbols(NumberOfSymbols, Symbol)

05.1 NumberOfSpaces ← AdjustedNumberOfSpaces(NumberOfSpaces)

05.2 NumberOfSymbols ← AdjustedNumbeOfSymbols(NumberOfSymbols)

06 UNTIL NumberOfSymbols > MaxNumberOfSymbols

Module definitions:

PROCEDURE SetValues(Symbol, MaxNumberOfSymbols, NumberOfSpaces, NumberOfSymbols)


INPUT Symbol

MaxNumberOfSymbols ← ValidatedMaxNumberOfSymbols

NumberOfSpaces ← (MaxNumberOfSymbols - 1) / 2

NumberOfSymbols ← 1

ENDPROCEDURE

FUNCTION ValidatedMaxNumberOfSymbols RETURNS INTEGER

REPEAT

INPUT MaxNumberOfSymbols

UNTIL MaxNumberOfSymbols MOD 2 = 1

RETURN MaxNumberOfSymbols

ENDFUNCTION

PROCEDURE OutputSpaces(NumberOfSpaces)

FOR Count1 ← 1 TO NumberOfSpaces

OUTPUT Space // without moving to next line

NEXT Count1

ENDPROCEDURE

PROCEDURE OutputSymbols(NumberOfSymbols, Symbol)

FOR Count2 ← 1 TO NumberOfSymbols

OUTPUT Symbol // without moving to next line

NEXT Count2

OUTPUT Newline // move to the next line

ENDPROCEDURE

FUNCTION AdjustedNumberOfSpaces(NumberOfSpaces) RETURNS INTEGER

NumberOfSpaces ← NumberOfSpaces – 1

RETURN NumberOfSpaces

ENDFUNCTION
FUNCTION AdjustedNumbeOfSymbols(NumberOfSymbols) RETURNS INTEGER

NumberOfSymbols ← NumberOfSymbols + 2

RETURN NumberOfSymbols

ENDFUNCTION

Note that the procedure OutputSpaces uses a variable, Count1, which is used only within the module. Similarly,
OutputSymbols uses variable Count2 only within the module. We call such a variable a local variable (a variable that
is accessible only within the module in which it is declared. Tip: Good design uses local variables as it makes modules independent and re-
usable. ) A variable available to all modules is known as a global variable (a variable that is accessible from all modules)

You might also like