Lecture 6
Lecture 6
2
How to Solve Problems
Problem: Your hair are dirty, and you want to clean your hair
3
How to Solve Problems
Problem: Hair are dirty
Solution: Clean hair
How: “Wash the hair” algorithm
Algorithm;
Turn on water tab
Wet your hair
Apply shampoo
Rinse
Dry off
4
How to Solve Problems
Problem: How to make a brownie?
Solution: ??
5
Algorithms
We are given a problem to solve:
Understand and analyze the problem and its requirements
Like in the case of dirty hair, the requirement is the clean hair
Devise steps to solve a problem
6
Algorithms
Characteristics of algorithms;
Definite and having input and output
Well-ordered, the steps are in a clear order
Unambiguous, the operations described are understood by a computing agent without further simplification
Effectively computable, the computing agent can carry out the operation
7
Algorithms vs Pseudocode
Pseudocode is an artificial and informal language that helps in developing algorithms
It is a method of writing an algorithm that may be in informal English, combinations of computer and/or
spoken languages (whatever works for you)
Algorithm is a systematic logical approach used to solve problems while Pseudocode are statements in natural
language (syntax of communication) about solving a problem
8
Algorithms
Example: Write an algorithm to determine a student’s final score* and then print it to the output screen
* the final score is calculated as the average of the four subjects marks
Pseudocode
Input a set of 4 marks (numbers)
Calculate their average, add all the numbers and divide by 4
Print average
Algorithm
START
Step 1: INPUT n1, n2, n3, n4
Step 2: score ← (n1+n2+n3+n4)/4
Step 3: PRINT score
END
9
Rules of Algorithms
Input:
use keyword “INPUT” or “GET” followed by a list of variables separated by a single comma
Examples:
INPUT a
INPUT a, b
GET a
GET a, b
10
Rules of Algorithms
Output:
use keyword “OUTPUT”, “DISPLAY”, “WRITE”, or “PRINT” followed by a variable name or text
enclose “text/message” in inverted commas
do not enclose variable name in inverted commas
Examples:
OUTPUT “Enter a number”
DISPLAY “Your number is ” num
11
Rules of Algorithms
Storage/Assignment:
to give an initial value, use ‘INITIALIZE’ or ‘SET’ in combination with “=”, “:=” or use keyword “=”,
“:=”, “<-”
to keep a variable for later use, use ‘SAVE’ or ‘STORE’
Examples:
INITIALIZE x
SET x = 8
x=8
SET x := 8
x := 8
x <- 8
12
Rules of Algorithms
Arithmetic operations:
use different mathematics symbols or expressions
Logical (or comparison) operations:
use logical and comparison operators
Examples:
x = 5, y = 7
x > y or x < y
z=x+y
z = 12
13
Structure Theorem
A structure theorem states that it is possible to write any algorithm by using only three basic control
structures;
1. Sequence
I must study classes from grade 1 to grade 10
I cannot skip any class in order to reach in grade 10
2. Repetition
If I am failed in a grade, I must repeat it until pass
3. Selection
I have passed my 10th grade, now I must select between Science and Arts groups
14
Structure Theorem
Sequence is an ordered list of steps to be executed
It determines an order in which one step follows the other
For example, you can not calculate average if you don’t have a series of numbers (at least 2) as input etc.
15
Structure Theorem (Repetition)
FOR is a loop that allows steps to be repeatedly executed
it is typically used when the number of iterations are known beforehand
Example:
FOR (number=1; number<10; number++)
DISPLAY number
END FOR
16
Structure Theorem (Repetition)
WHILE is a control flow statement that allows steps to be executed repeatedly based on a given condition
Example:
number = 1
WHILE (number<10)
DISPLAY number
number = number + 1
END WHILE
17
Structure Theorem (Repetition)
DO WHILE is a statement that performs the action(s) at least once
Example:
number = 1
DO
DISPLAY number
number = number + 1
WHILE (number<10)
18
Structure Theorem (Repetition)
Example: Write an algorithm to read and print 10 records using the while loop
START
SET total = 0
WHILE (total < 10)
READ record
PRINT record
total = total + 1
END WHILE
END
19
Structure Theorem (Selection)
Sometimes we need to put certain condition(s) before performing an action
If the condition(s) is ‘true’, then action will be executed, else not
Selection compares two pieces of information and select one of the two alternatives
It is represented by the IF statement and keywords IF, THEN, ELSE and ENDIF
IF statement always has a condition to check, often a comparison between a variable and a number
The IF statement also must specify what to do if the condition/comparison is true
These instructions (for “true”) comes after the word THEN
20
Structure Theorem (Selection)
IF – THEN – END IF (Single IF)
Single IF selection statement either performs an action if a condition is true or skips the action if the condition is false
21
Structure Theorem (Selection)
Single IF
IF (condition) THEN
<<steps>>
END IF
Double IF
IF (condition) THEN
<<steps>>
ELSE
<<steps>>
END IF
22
Structure Theorem (Selection)
Multiple IF Nested IF
IF (condition) THEN IF (condition) THEN
<<steps>> IF (condition) THEN
ELSE IF (condition) THEN <<steps>>
<<steps>> ELSE
ELSE IF (condition) THEN <<steps>>
<<steps>> END IF
ELSE ELSE
<<steps>> <<steps>>
END IF END IF
23
Structure Theorem (Selection)
Example: Write an algorithm to determine if a student has passed* a subject and print it to the output
screen
*the passing marks are 50 and above
Pseudocode
Input marks (a number)
If the marks are 50 or above, print “PASS”
Algorithm
START
Step 1: INPUT marks
Step 2: IF (marks >= 50) THEN
PRINT “PASS”
END IF
END
24
Structure Theorem (Selection)
Example: Write an algorithm to determine a student’s final score*, indicate whether the student is pass or
fail**, and print it to the output screen
*the final score is calculated as the average of the four subjects marks
**the passing marks are 50 and above
Pseudocode
Input a set of 4 marks (numbers)
Calculate their average, add all the numbers and divide by 4
If average is below 50, print “FAIL”, else, print “PASS”
25
Structure Theorem (Selection)
Example: Write an algorithm to determine a student’s final score*, indicate whether the student is pass or
fail**, and print it to the output screen
*the final score is calculated as the average of the four subjects marks
**the passing marks are 50 and above
Algorithm
START
Step 1: INPUT n1, n2, n3, n4
Step 2: score ← (n1+n2+n3+n4)/4
Step 3: IF (score < 50) THEN
PRINT “FAIL”
ELSE
PRINT “PASS”
END IF
END 26
Structure Theorem (Selection)
Example: Write an algorithm to determine a student’s final score*, determine whether the student is pass or
fail**, if the student is pass, calculate the student’s grade (based on the criterion given below), and print the
grade to the output screen
*the final score is calculated as the average of the four subjects marks
**the passing marks are 50 and above
27
Structure Theorem (Selection)
Algorithm
START
Step 1: INPUT n1, n2, n3, n4 ELSE IF (score >= 90 && score <= 100)
PRINT “Grade is D”
ELSE IF (score >= 70 && score <= 79)
PRINT “Grade is C”
ELSE IF (score >= 80 && score <= 89)
PRINT “Grade is B” 28
Structure Theorem (Repetition+Selection)
Example: Write a WHILE loop structure that displays any number input by the user on the screen and only
terminates when the user enters a sentinel value (assume the sentinel value to be -1)
INPUT a
WHILE (a != -1)
DISPLAY a
INPUT a
END WHILE
29
Flowchart
Flowchart is a graphical representation that shows logic solution
Emphasizes individual steps and their interconnections
It must have a start and stop step
All steps in a flowchart must connect, i.e., you can’t leave a step “hanging” with no connection
30
Flowchart (Symbols)
Start/End
used at the beginning and end of each flowchart
Input/Output
shows when data comes in or information is printed out
Process
used to show calculations, storing of data in variables, and other “processes”
Decision
used to show that the flow must decide whether
something (usually a comparison between numbers) is true or false
Connector
used to show that flowchart continues another page
Flow Direction
shows the direction of flow
31
Flowchart
Example: Write an algorithm and draw flowchart that inputs two numbers from the user, multiply it, and
print the answer to the screen
Algorithm Flowchart
START START
Step 1: INPUT w, m
Step 2: a ← m x w Input w, m
Step 3: PRINT a
a¬mxw
END
PRINT a
END
32
Flowchart
Example: Write an algorithm and draw flowchart to determine a student’s final score and indicate whether
the student is pass or fail, and print it to the output screen
Algorithm Flowchart
START
START
PRINT “FAIL”
IF
ELSE grade<50
PRINT “PASS”
PRINT “FAIL” PRINT “PASS”
END IF
END
END
33
Trace Tables & Dry Run
Dry run
working through a section of an algorithm (program) manually
Trace table
a technique used to test algorithms to make sure they work without any error
35
Trace Tables & Dry Run
Example: Following is an algorithm that take five numbers as input from the user, calculates and display their
sum and average. Make trace table for the algorithm
Algorithm
START
Step 1: SET sum := 0, average := 0, totalNumbers :=5
Step 2: INPUT n1, n2, n3, n4, n5
Step 3: sum := n1 + n2 + n3 + n4 + n5
Step 4: average := sum / totalNumbers
Step 5: PRINT “Sum is ” sum
Step 6: PRINT “Average is ” average
END
36
Trace Tables & Dry Run
Trace Table
37
THANK YOU
38