Week 1: Problem-Solvingand Algorithm
1. Computing Fundamentals
2. Problem-Solving
3. Algorithm
4. Control Structures
5. Tasks: Writing Algorithms in Pseudo-code
This symbol indicates the focus of today’s lesson.
3.
Computing Fundamentals
Software
Keyboard and
mouse(input)
Monitor
and
speaker
(output)
Houses processor,
memory, buses, etc.
Hardware
▪ Set of instructions to perform
tasks to specifications
▪ Programs are software
4.
Software (1/4)
■ Program
◻Sequence of instruction that tells a computer what to do
■ Execution
◻ Performing the instruction sequence
■ Programming language
◻ Language for writing instructions to a computer
■ Major flavors
◻ Machine language or object code
◻ Assembly language
◻ High-level
5.
Software (2/4)
■ Program
◻Sequence of instruction that tells a computer what to do
■ Execution
◻ Performing the instruction sequence
■ Programming language
◻ Language for writing instructions to a computer
■ Major flavors
◻ Machine language or object code
◻ Assembly language
◻ High-level
Program to which computer can
respond directly. Each instruction
is a binary code that corresponds
to a native instruction.
Example: 0001001101101110
6.
Software (3/4)
■ Program
◻Sequence of instruction that tells a computer what to do
■ Execution
◻ Performing the instruction sequence
■ Programming language
◻ Language for writing instructions to a computer
■ Major flavors
◻ Machine language or object code
◻ Assembly language
◻ High-level
Symbolic language
for coding machine
language instructions.
Example: ADD A, B, C
7.
Software (4/4)
■ Program
◻Sequence of instruction that tells a computer what to do
■ Execution
◻ Performing the instruction sequence
■ Programming language
◻ Language for writing instructions to a computer
■ Major flavors
◻ Machine language or object code
◻ Assembly language
◻ High-level
Detailed knowledge of the machine
is not required. Uses a vocabulary
and structure closer to the problem
being solved.
Examples: Java, C, C++,
Prolog, Scheme.
8.
Translation
■ High-level languageprograms (source codes) must
be translated into machine code for execution
■ Translator
◻ Accepts a program written in a source language and
translates it to a program in a target language
■ Compiler
◻ Standard name for a translator whose source language is
a high-level language
■ Interpreter
◻ A translator that both translates and executes a source
code
Pólya: How toSolve It (1/5)
A great discovery solves a great problem but there is a
grain of discovery in the solution of any problem.
Your problem may be modest; but if it challenges your
curiosity and brings into play your inventive faculties,
and if you solve it by your own means, you may
experience the tension and enjoy the triumph of
discovery.
Such experiences at a susceptible age may create a
taste for mental work and leave their imprint on mind
and character for a lifetime.
– George Pólya
12.
Pólya: How toSolve It (2/5)
■ Phase 1: Understanding the problem
■ Phase 2: Devising a plan
■ Phase 3: Carrying out the plan
■ Phase 4: Looking back
◻ What is the unknown? What are the data?
◻ What is the condition? Is it possible to satisfy the
condition? Is the condition sufficient to determine the
unknown?
◻ Draw a figure. Introduce suitable notation.
13.
Pólya: How toSolve It (3/5)
■ Phase 1: Understanding the problem
■ Phase 2: Devising a plan
■ Phase 3: Carrying out the plan
■ Phase 4: Looking back
◻ Have you seen the problem before? Do you know a related
problem?
◻ Look at the unknown. Think of a problem having the same or
similar unknown.
◻ Split the problem into smaller sub-problems.
◻ If you can’t solve it, solve a more general version, or a
special case, or part of it.
14.
Pólya: How toSolve It (4/5)
■ Phase 1: Understanding the problem
■ Phase 2: Devising a plan
■ Phase 3: Carrying out the plan
■ Phase 4: Looking back
◻ Carry out your plan of the solution. Check each step.
◻ Can you see clearly that the step is correct?
◻ Can you prove that it is correct?
15.
Pólya: How toSolve It (5/5)
■ Phase 1: Understanding the problem
■ Phase 2: Devising a plan
■ Phase 3: Carrying out the plan
■ Phase 4: Looking back
◻ Can you check the result?
◻ Can you derive the result differently?
◻ Can you use the result, or the method, for some other
problem?
16.
Algorithmic Problem Solving
■An algorithm is a well-defined computational
procedure 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.
Input Output
Algorithm
17.
Algorithm
■ Each stepof an algorithm must be exact.
■ An algorithm must terminate.
■ An algorithm must be effective.
■ An algorithm must be general.
■ Can be presented in pseudo-code or flowchart.
Exact
Terminat
e
Effective General
18.
Find maximum andaverage of a list of numbers (1/2)
■ Pseudo-code
sum ← count ← 0 // sum = sum of numbers
// count = how many
numbers are entered?
max ← 0 // max to hold the
largest value eventually
for each num entered,
count ← count + 1
sum ← sum + num
if num > max
then max ← num
ave ← sum / count
print max, ave
Are there any errors
in this algorithm?
The need to initialise variables.
The need to indent.
19.
Find maximum andaverage of a list of numbers
(1/2)
■ Flowchart start
sum ← count ← 0
max ← 0
end of
input?
increment count
sum ← sum + num
Yes
No
No
num > max?
Yes
No
max ← num
ave ← sum/count
end
Terminator box
Process box
Decision box
print max, ave
Data Representation
■ Internalrepresentation: bits (binary digits) 0 and 1
❑ 1 byte = 8 bits
❑ We will not deal with bit level and bit operations
■ Data types (lists here are not exhaustive):
❑ Integers: int, short, long
❑ Real numbers: float, double
❑ Characters: char
■ Read up Lesson 1.4 in reference book on your own
■ A variable holds some data and it belongs to a data
type and occupies some memory space, shown as a
box in the following slides.
22.
Algorithm: Example #1(1/2)
■ Example 1: Compute the average of three integers.
A possible algorithm:
enter values for num1, num2,
num3
ave ← ( num1 + num2 + num3 ) /
3
print ave
num1
Variables used:
num2 num3
ave
Another possible algorithm:
enter values for num1, num2,
num3
total ← ( num1 + num2 + num3 )
ave ← total / 3
print ave
num1
Variables used:
num2 num3
ave
total
Sequence
23.
Algorithm: Example #1(2/2)
■ How the code might look like
// This program computes the average of 3 integers
#include <stdio.h>
int main(void) {
int num1, num2, num3;
float ave;
printf("Enter 3 integers: ");
scanf("%d %d %d", &num1, &num2, &num3);
ave = (num1 + num2 + num3) / 3.0;
printf("Average = %.2fn", ave);
return 0;
}
Week1_prog1.c
Sequence
24.
Algorithm: Example #2(1/3)
■ Example 2: Arrange two integers in increasing order
(sort).
Algorithm A:
enter values for num1, num2
// Assign smaller number into final1,
// larger number into final2
if (num1 < num2)
then final1 ← num1
final2 ← num2
else final1 ← num2
final2 ← num1
// Transfer values in final1, final2 back to num1,
num2
num1 ← final1
num2 ← final2
// Display sorted integers
print num1, num2
Variables used:
num1 num2
final1 final2
Selection
25.
Algorithm: Example #2(2/3)
■ Example 2: Arrange two integers in increasing order
(sort).
Algorithm B:
enter values for num1, num2
// Swap the values in the variables if
necessary
if (num2 < num1)
then temp ← num1
num1 ← num2
num2 ← temp
// Display sorted integers
print num1, num2
Variables used:
num1 num2
temp
Selection
26.
Algorithm: Example #2(3/3)
■ How the code might look like (for algorithm B)
// This program arranges 2 integers in ascending order
#include <stdio.h>
int main(void) {
int num1, num2, temp;
printf("Enter 2 integers: ");
scanf("%d %d", &num1, &num2);
if (num2 < num1) {
temp = num1; num1 = num2; num2 = temp;
}
printf("Sorted: num1 = %d, num2 = %dn", num1,
num2);
return 0;
}
Week1_prog2.c
Selection
27.
Algorithm: Example #3(1/2)
■ Example 3: Find the sum of positive integers up to n
(assuming that n is a positive integer).
Algorithm:
enter value for n
// Initialise a counter count to 1, and ans to 0
count ← 1
ans ← 0
while (count <= n) do the following
ans ← ans + count // add
count to ans
count ← count + 1 // increase
count by 1
// Display answer
print ans
Variables used:
n
count
ans
Repetition
28.
Algorithm: Example #3(2/2)
■ How the code might look like
// Computes sum of positive integers up to n
#include <stdio.h>
int main(void) {
int n; // upper limit
int count=1, ans=0; // initialisation
printf("Enter n: ");
scanf("%d", &n);
while (count <= n) {
ans += count;
count++;
}
printf("Sum = %dn", ans);
return 0;
}
Week1_prog3.c
Repetition
29.
Euclidean algorithm
■ Firstdocumented algorithm by Greek mathematician
Euclid in 300 B.C.
◻ To compute the GCD (greatest common divisor) of two integers.
1. Let A and B be integers with A > B ≥ 0.
2. If B = 0, then the GCD is A and algorithm ends.
3. Otherwise, find q and r such that
A = q.B + r where 0 ≤ r < B
4. Replace A by B, and B by r. Go to step 2.
30.
Step-wise Refinement (1/3)
■From the examples, we see that in general an algorithm
comprises three steps:
❑ Input (read data)
❑ Compute (process input data to generate some answers)
❑ Output (display answers)
■ The ‘compute’ step is the most complex.
■ Step-wise refinement – break down a complex step into
smaller steps.
31.
Step-wise Refinement (2/3)
■Example: Given a value in miles, convert it into
kilometres
■ Recall Phase 1 of “How To Solve It”: Understanding the
problem.
❑ Is the problem clear? If not, ask questions!
■ One possible algorithm:
1. Read in distance (m) in miles // step 1: input
2. Convert the distance to kilometres (k) // step 2:
compute
3. Print the distance (k) in kilometres // step 3: output
32.
Step-wise Refinement (3/3)
■We can actually stop here, if we are clear about how to
do each step.
■ If not, we need to refine the step. For instance, step 2,
how do we convert miles to kilometres
❑ we refine step 2 to:
1. Read in distance (m) in miles // step 1: input
2. Convert the distance to kilometres // step 2: compute
2.1 calculate k = m * 1.609
3. Print the distance (k) in kilometres // step 3: output
33.
Tasks for practiceon Problem-
solving and writing Algorithms in
Pseudo-code
34.
Task 1: Areaof a Circle (1/2)
■ What is the data? Side of
square = 2a
■ What is the unknown? Area
of circle, C.
■ What is the condition? If
radius r is known, C can be
calculated.
■ How to obtain r?
2a
35.
Task 1: Areaof a Circle (2/2)
■ Pythagoras’ theorem:
■ Area of circle
a
a r
◈
36.
Task 2: CoinChange
■ Given these coin denominations: 1¢, 5¢,
10¢, 20¢, 50¢, and $1, find the smallest
number of coins needed for a given
amount. You do not need to list out what
coins are used.
◻ Example 1: For 375 cents, 6 coins are needed.
◻ Example 2: For 543 cents, 10 coins are needed.
37.
Task 2: CoinChange – A possible algorithm
Week1 - 37
◈
38.
Task 3: BreakingUp an Integer
■ A common sub-task in many problems involves number
manipulation
Week1 - 38
252040312
2 2 2
5
0 0
4 3
1
■ Example: Given a positive integer n, how do you sum
up all its individual digits?
❑ The answer for the above example is 19 (2 + 5 + 2 + 0 + 4 + 0
+ 3 + 1 + 2)
39.
Algorithm before coding
■The earlier examples show that we can discuss problems and
their solutions (algorithms) without writing out the codes.
■ A sample program development process:
❑ Understanding the problem (if in doubt, ask questions!): 5 minutes
❑ Writing the algorithm: 30 minutes
❑ Testing the algorithm: 20 minutes
❑ Writing the program: 20 minutes
❑ Testing and debugging the program: 30 minutes to 3 hours or more
■ For more complex problems, time spent in thinking about the algorithm
could far exceed time spent in writing the program.
■ The more time you invest in writing a good algorithm, the more time you
will save in debugging your program.
40.
Quotes for CS1010Students
■Before you succeed, you must fail many times.
■Don’t ask me what this code does, trace it
yourself!
■Think! Think! Think!
■Practise! Practise! Practise!
■It’s all about logic. Every step must be clear to
you.