You are on page 1of 52

COMP1205:

Program Design and Algorithms


Objectives

• Introduce common words, keywords, and meaningful names


when writing pseudocode
• Define the three basic control structures as set out in the
Structure Theorem
• Illustrate the three basic control structures using
pseudocode
Six Basic Computer Operations

1 A computer can receive information


• When a computer is required to receive information or
input from a particular source, whether it is a terminal,
a disk or any other device, the verbs Read and Get are
used in pseudocode

Read => Input from a record Example pseudocode


Get => Input from keyboard
Read student name
Get system data
Read number1, number2
Get tax_code

Simple Program Design, Fourth Edition Chapter 2 3


Six Basic Computer Operations

1 A computer can receive information


• Usually an output Prompt instruction is required before
an input Get instruction

Example pseudocode

Prompt for student_mark


Get student_mark

Simple Program Design, Fourth Edition Chapter 2 4


Six Basic Computer Operations

2 A computer can put out information


• When a computer is required to supply information or
output to a device, the verbs Print, Write, Put, Output,
or Display are used in pseudocode
• Print => send output to printer
• Write => send out to file
Example pseudocode
Print ‘Program Completed’
Write customer record to master file
Output total tax
• Put, Output, Display => send to screen
Display ‘End of data’

Simple Program Design, Fourth Edition Chapter 2 5


Six Basic Computer Operations

3 A computer can perform arithmetic


• Most programs require the computer to perform some sort
of mathematical calculation, or formula, and for these, a
programmer may use either actual mathematical symbols or
the words for those symbols
• To be consistent with high-level programming languages, the
following symbols can be written in pseudocode:
+ for Add - for Subtract
* for Multiply / for Divide ( ) for Parentheses
• When writing mathematical calculations for the computer,
standard mathematical ‘order of operations’ applies to
pseudocode and most computer languages

6
Six Basic Computer Operations

4 A computer can assign a value to a variable or memory location


• There are three cases where you may write pseudocode to
assign a value to a variable or memory location:
1. To give data an initial value in pseudocode, the verbs
Initialize or Set are used
2. To assign a value as a result of some processing the
symbols ‘=‘ or ‘’ are written
3. To keep a variable for later use, the verbs Save or Store
are used

7
Six Basic Computer Operations

4 A computer can assign a value to a variable or memory


location
Example pseudocode

Initialize total_price to zero


Set student_count to zero
Total_price = cost_price + sales_tax
Total_price  cost_price + sales_tax
Store customer_num in last_customer_num

Simple Program Design, Fourth Edition Chapter 2 8


Six Basic Computer Operations

5 A computer can compare two variables and select one or


two alternate actions

• An important computer operation available to the


programmer is the ability to compare two variables
and then, as a result of the comparison, select one of
two alternate actions

• To represent this operation in pseudocode, special


keywords are used: IF, THEN, and ELSE

9
Six Basic Computer Operations

6 A computer can repeat a group of actions

• When there is a sequence of processing steps that


need to be repeated, two special keywords, DOWHILE
and ENDDO, are used in pseudocode

• The condition for the repetition of a group of actions is


established in the DOWHILE clause, and the actions to
be repeated are listed beneath it

10
The Structure Theorem

• The Structure Theorem states that it is possible to write any


computer program by using only three basic control
structures that are easily represented in pseudocode:
• Sequence
• Selection
• Repetition

Simple Program Design, Fourth Edition Chapter 2 11


The Three Basic Control Structures

1. Sequence
• The sequence control structure is the straightforward
execution of one processing step after another
• In pseudocode, we represent this construct as a
sequence of pseudocode statements

12
The Three Basic Control Structures

2. Selection
• The selection control structure is the presentation of a
condition and the choice between two actions; the
choice depends on whether the condition is true or
false
• In pseudocode, selection is represented by the
keywords IF, THEN, ELSE, and ENDIF

13
The Three Basic Control Structures

3 Repetition

• The repetition control structure can be defined as the


presentation of a set of instructions to be performed
repeatedly, as long as a condition is true

• The basic idea of repetitive code is that a block of statements


is executed again and again, until a terminating condition
occurs

• This construct represents the sixth basic computer operation,


namely to repeat a group of actions

14
Checkpoint

• So far, six basic computer operations were listed, along with


pseudocode words and keywords to represent them
• These operations were: to receive information, put out
information, perform arithmetic, assign a value to a variable,
decide between two alternate actions, and repeat a group of
actions
• The Structure Theorem was introduced; it states that it is possible
to write any computer program by using only three basic control
structures: sequence, selection, and repetition

Simple Program Design, Fourth Edition Chapter 2 15


Question

• What steps do you take to solve a problem?


Strategies
Problem Solving
• Problem solving and software development
• A typical software life cycle
• Problem solving process
• A typical software life cycle
• How we develop software
• Design and analysis

18 COMP1105
Problem solving and software development

• Software Development
• Small programs (less than 5000 lines) can be reliably developed and
tested by one person

• Most software is developed in much larger environments - with


teams of programmers or even collections of teams
• Windows operating system has roughly 50 million lines of code
• Android is about 12 million linesof code

• Managing large projects involves many organisational difficulties

19 COMP1105
Problem solving and software development
• Software Engineering
• Software engineering (SE) is concerned with developing and
maintaining software systems that behave reliably and
efficiently, are affordable to develop and maintain, and
satisfy all the requirements that customers have defined for
them.

• It is about LARGE and REAL systems!

• The skills start here

20 COMP1105
Problem solving process
• You need good problem solving skills to develop software
• This is NOT about learning things by rote
• To survive you MUST be able to tackle large complex problems
• If do not design and document now, you will fail in the workplace
• Imagine Microsoft Office written with no planning, organisation,
and documentation (30+ million lines of code)
• Parts written in C++
• Maintenance and debugging --> sleepless nights deciphering code!

21 COMP1105
Problem Solving: A typical software life cycle

• Analysis - specifying exactly what the problem is and what are


the requirements for an acceptable solution
• Design - developing a detailed solution to the problem
• Coding - turning the design into a working program
• Testing/Verification - ensuring the software is correct
• Maintenance - fixing, enhancing, adapting the software
• Obsolescence - abandoning a program which is no longer
effectively maintainable
22 COMP1105
Problem Solving: Historical view of software
life cycle

The Waterfall
Model

23 COMP1105
Problem Solving: How we develop software

• Understand and define the questions being asked


• Analyse the problem given
• Develop a solution technique (algorithm)
• Document the program/technique
• Translate (implement) the technique into code
• Compile and run the program
• Test the results with appropriate data
24 COMP1105
Problem Solving: Design and analysis

• A very important first step is to understand


• ask questions
• Then analysis includes:
• determining the input data for the program
• determining the output that must be produced
• identifying any information needed to get from the inputs to
the output
• Design consists primarily of working out an algorithm
• step-by-step procedure to solve the problem (based on
analysis)
25 COMP1105
Structured Programming
• Algorithms
• Pseudocode
• Flowcharts

• Create a design with Sequence, Selection, Repetition

26 COMP1105
Algorithms
• Must be:
• Precise and unambiguous
• Give the correct solution in all cases
• Eventually end
Example: Describe the steps involved in going to the airport
from UWI

27 COMP1105
Algorithms
• Must be:
• Precise and unambiguous
• Give the correct solution in all cases
• Eventually end
Example: Describe the steps for passing CXC English

28 COMP1105
Algorithms
• Must be:
• Precise and unambiguous
• Give the correct solution in all cases
• Eventually end
Example: Give the algorithm for calculating simple interest on a loan

29 COMP1105
Algorithm Representation
• Words
• Pseudocode

• Diagrams
• Flow Charts

30 COMP1105
How to Write Pseudocode

• When designing a solution algorithm, you need to keep in


mind that a computer will eventually perform the set of
instructions written

• If you use words and phrases in the pseudocode which are


in line with basic computer operations, the translation from
pseudocode algorithm to a specific programming language
becomes quite simple

Simple Program Design, Fourth Edition Chapter 2 31


Defining Problem (Example)
A fabric store wants a program to convert measurements from square
metres to square yards

Define problem – program data?


Inputs: the incoming information is the number of square metres of fabric
Outputs: the number of square yards which are equivalent to the input
number of square metres
Inputs Processing Outputs
square Meters ? squareYards

How to get from inputs to outputs: the extra information we need (and can
work out) is that 1 square metre = 1.196 square yards.
So the processing is to multiply 1.196 by the input number
32 COMP1105
Pseudocode (Example 1)
An accountant needs a program to read 2 numbers, add them and
print their total.
Defining Diagram

Algorithm
Algorithm to add 2 numbers and print their sum
Begin
Define variables Num1, Num2, Sum as whole numbers
Print “Please enter two integers”
Get Num1
Get Num2
Sum <- Num1 + Num2
33
Display Sum
End COMP1105
Pseudocode (Example 2)
The same accountant needs to print the larger of the two numbers (if any).

Begin
Get Num1 from the keyboard
Get Num2 from the keyboard
IF Num1 is greater than Num2 THEN
print Num1
ELSE
IF Num2 is greater than Num1 THEN
print Num2
ELSE
Display “The numbers are equal”
ENDIF
34 ENDIF COMP1105

End
Flowchart
• Graphical representation of an algorithm using special-purpose
symbols connected by arrows (flowlines)

• Parallelogram symbol –
Input/Output operations Prompt user for Num2, Num1

• Diamond symbol - Decision Read Num2, Num1

• Rectangle symbol – Action/process no What to do?


Num1 > Num2

• Oval symbol – Beginning or end yes


of a program, or a section of
code (circles) Print Num1
35

Stop
if Selection structure****
Choose among alternative courses of action
• Example:
◙ Pseudocode statement to determine whether a student
has passed the course:
IF (student’s coursework grade is greater than OR equal to 50) AND
(student’s exam grade is greater than OR equal to 50)
THEN
Print “Passed”
• If the condition is true
• “Passed” is printed, control continues on to next statement
• If the condition is false
• Print statement ignored, control continues to statement after the if
• NB: Indenting makes algorithm easier to read
36 COMP1105
if Selection structure
If - Performs action if
condition true
• Flowchart of previous if/else – Performs
pseudocode statement Different actions if conditions
true or false

Example:

both grades IF (student’s coursework grade is


yes greater than OR equal to 50)
greater than 50 print
“Passed” AND (student’s exam grade is
greater than OR equal to 50)
THEN
no print “Passed”
ELSE
37 COMP1105
print “Failed”
ENDIF
while Repetition Structure

• Action repeated while some condition remains true


• Pseudocode
DOWHILE there are more items on my shopping list
Purchase the next item and cross it off the list
EndDO
• while loop repeated until condition becomes false

More true Purchase the next item


items on list? and cross it off the list
38 COMP1105

false
Let’s Look at an Algorithm
Strongest student in the class
Write an algorithm to record the strongest
Begin Algorithm
Declare variables
Prompt user for number of people in class

person in the class!


READ number of people into the variable people

Prompt user for first time-run, name


READ the first time directly into the variable slow_time
READ the first name directly into the variable slow_name
Initialise a counter to 1

Prompt user for time-run, name


READ the first time directly into the variable time
READ the first name directly into the variable name
Add 1 to counter
IF time_run is greater than slow_time
slow_time  time_run and slow_name  name
ENDIF

Prompt user for time-run, name


READ the first time directly into the variable time
READ the first name directly into the variable name
Add 1 to counter

DOWHILE counter is less than or equal to people


Prompt user for time, name
READ a new time into the variable time_run
READ a new name into the variable name
IF time_run is greater than slow_time
slow_time  time_run and slow_name  name
ENDIF
40 COMP1105
Increment counter
End DoWhile
Print “Congrats “ strong_name “you are te strongest at” most_weight_lift “lbs!”
End Algorithm
Flowchart: Oldest Person

START

Read people

Read age increment counter

counter = 1
no
yes
oldest = age counter <= people Read age age > oldest

no yes
print oldest
oldest = age
END
41 COMP1105
Your turn 
Tallest person in the class
Solve this problem

• Let’s write the algorithm in pseudocode to ask the user for 20


numbers
• Read in those 20 numbers
• Ask the user to have a friend input a guess of a number within
those numbers
• Check to see if that guess is in the 20.
• If it is, then print “CONGRATS, You’ve Got it!”
• The game is done done
• Draw a flowchart for this

43 COMP1105
A Guide
For writing Pseudocode
Guidelines for pseudocode
• Declaration
• Format: Declare <variable name> of type <variable type>
• Examples
Declare variable total of type integer 
Declare variable length of type float 
Declare variable name of type string
Declare variable continue of type character

45 COMP1105
Guidelines for pseudocode
• Assignment
• Formatvariable = expression
• Examples
total = 0 
y=x*x+z/4-1
name = "Joan Smith"
validLength = True

46 COMP1105
Guidelines for pseudocode
• Input
• Format: Input variable, variable, ...
• Examples
• Input custName
Input distance, speed
• Read custName
Read distance, speed

47 COMP1105
Guidelines for pseudocode
• Display
• Format: Display value, value, ...

Examples
• Display "Hello World" 
Display totalPrice, taxPayable 
Display "Customer Number: ", custNum, "Name: ", custName

48 COMP1105
Guidelines for pseudocode
• If –Else format
• IF condition THEN
    statement 
    statement 
    ... 
ENDIF 
• IF condition THEN
    statements 
ELSE
    IF condition THEN
        statements 
    ENDIF
ENDIF
49 COMP1105
Guidelines for pseudocode
• Examples
• IF lineNumber > 50 THEN
    Display ""
    Display "Student Number", "Student Name"
    lineNumber = 0 
ENDIF 

50 COMP1105
Guidelines for pseudocode

• A FOR loop is another kind of loop


• Format
• FOR counter = start-value to end-value DO 
    statement 
    statement 
    ... 
ENDFOR
• Example
• FOR x = 1 to 10 DO 
    xSquared = x * x 
    Display x, xSquared 
51
ENDFOR COMP1105
Guidelines for pseudocode

• While
• WHILE condition DO 
    statement 
    statement 
    ... 
ENDWHILE
• Example
• count = 1 
WHILE count <= 10 DO 
    Display count 
    Add 1 to count 
ENDWHILE
52 COMP1105

You might also like