Transcript Slide 1

TK 1914 : C++ Programming
Algorithms and Problem Solving
WHAT IS AN ALGORITHM?
• An algorithm is a set of ordered steps for solving a
problem.
• Examples:
• An algorithm for preparing breakfast.
• An algorithm for converting Gregorian dates
to Islamic dates.
• An algorithm for calculating moon phase.
• An algorithm for drawing a curve.
FTSM :: TK1914 20112012
2
ALGORITHM IN REAL LIFE
• Consider the following …
Problem: Baking a Cake
How to solve:
1. Start
2. Preheat the oven at 180oC
3. Prepare a baking pan
4. Beat butter with sugar
5. Mix them with flour, eggs and essence vanilla
6. Pour the dough into the baking pan
7. Put the pan into the oven
8. End
FTSM :: TK1914 20112012
3
‘DIVIDE AND CONQUER’ STRATEGY
IN ALGORITHM
Problem: Prepare a Breakfast
1. Start
2. Prepare a Breakfast
3. End
FTSM :: TK1914 20112012
4
‘DIVIDE AND CONQUER’ STRATEGY
IN ALGORITHM
1. Start
2. Prepare a Breakfast
2.1 Prepare a tuna sandwich
2.2 Prepare some chips
2.3 Make a cup of coffee
3. End
FTSM :: TK1914 20112012
5
‘DIVIDE AND CONQUER’ STRATEGY
IN ALGORITHM
1. Start
2. Prepare a Breakfast
2.1 Prepare a tuna sandwich
2.1.1 Take 2 slices of bread
2.1.2 Prepare tuna paste
2.2 Prepare some chips
2.3 Make a cup of coffee
3. End
FTSM :: TK1914 20112012
6
‘DIVIDE AND CONQUER’ STRATEGY
IN ALGORITHM
1. Start
2. Prepare a Breakfast
2.1 Prepare a tuna sandwich
2.1.1 Take 2 slices of bread
2.1.2 Prepare tuna paste
2.2 Prepare some chips
2.2.1 Cut potatoes into slices
2.2.2 Fry the potatoes
2.3 Make a cup of coffee
3. End
FTSM :: TK1914 20112012
7
‘DIVIDE AND CONQUER’ STRATEGY
IN ALGORITHM
1. Start
2. Prepare a Breakfast
2.1. Prepare a tuna sandwich
2.1.1 Take 2 slices of bread
2.1.2 Prepare tuna paste
2.2. Prepare some chips
2.2.1 Cut potatoes into slices
2.2.2 Fry the potatoes
2.3. Make a cup of coffee
2.3.1 Boil water
2.3.2 Add water with sugar and coffee
3. End
FTSM :: TK1914 20112012
8
CLASS ACTIVITY 5.1
• Write a simple algorithm for withdrawing
a sum of money at an ATM.
FTSM :: TK1914 20112012
9
WHY DO WE NEED TO BUILD
ALGORITHMS?
• If we wish to build a house, we need to design it
first.
– Can you think of some possible consequences of not
designing a house before building it?
• Similarly, computer programs (especially large and
complex ones) need to be designed before they are
written.
– Can you think of some possible consequences of not
designing a program before building it?
• One of the things considered when designing a
computer program is the algorithm which it will be
based on.
FTSM :: TK1914 20112012
10
ALGORITHMS IN PROGRAM DESIGN
• A computer program is built to solve a certain
problem.
Examples:
1. A program to calculate the grade obtained given
a mark.
2. A program to convert a Gregorian date to an
Islamic date.
3. A program to produce a document.
FTSM :: TK1914 20112012
11
• Below are steps (in fact, an algorithm) for
building a program to solve a particular problem:
– Analyse the problem
– Design a computer solution to the problem by
developing an algorithm.
– Write a computer program based on the algorithm.
– Test the program.
FTSM :: TK1914 20112012
12
HOW TO SPECIFY AN ALGORITHM?
• An algorithm must be specific enough so that it
can be conveniently translated into a computer
program (using C++, for example).
• An algorithm can be specified:
– Textually
For example, using pseudo code (see later)
– Graphically
For example, using flowcharts or UML activity charts
FTSM :: TK1914 20112012
13
FLOWCHARTS
• A flowchart is a graphical representation of the
sequence of operations in a program.
• An algorithm can be represented graphically using
a flowchart.
FTSM :: TK1914 20112012
14
FLOWCHART NOTATIONS
Symbol
Semantic
Start/End
Process
Input/Output
Test
Connector
Flow of activities
FTSM :: TK1914 20112012
15
FLOWCHART: EXAMPLE 1
Start
Algorithm starts here
Input
Gregorian date
Input data from user
Convert Gregorian
date to Islamic date
Perform the date conversion
Display
Islamic date
Display the result
Algorithm ends here
End
FTSM :: TK1914 20112012
16
PSEUDOCODE
• An outline of a program, written in a form that can
easily be converted into real programming
statements. It resembles the actual program that
will be implemented later. However, it cannot be
compiled nor executed.
• Pseudocode normally codes the following
actions:
– Initialisation of variables
– Assignment of values to the variables
– Arithmetic operations
– Relational operations
FTSM :: TK1914 20112012
17
EXAMPLE OF PSEUDOCODE
1. Start
2. Read quantity
3. Read price_per_kg
4. price  quantity * price_per_kg
5. Print price
6. End
FTSM :: TK1914 20112012
18
CLASS ACTIVITY 5.2
• Draw a flowchart which represents the algorithm
built in CA[5.1].
FTSM :: TK1914 20112012
19
FLOWCHART: EXAMPLE 2
Start
Input
length, width
area ← length X width
• length, width and
area are referred to
as variables.
• A variable is like a box
in which a value can
be stored
Output
area
End
FTSM :: TK1914 20112012
20
FLOWCHART: EXAMPLE 3
• Selection
Start
Input
height
false
height > 1.6?
Output
“You are short!”
true
Output
“You are tall!”
End
FTSM :: TK1914 20112012
21
FLOWCHART: EXAMPLE 4
• Repetition (looping)
Start
Output
“Thank you!”
Input
stop
false
stop = 1?
true
End
FTSM :: TK1914 20112012
22
PROBLEM SOLVING
FTSM :: TK1914 20112012
23
PROBLEM SOLVING
• Programming is a process of problem solving
• Problem solving techniques
– Analyze the problem
– Outline the problem requirements
– Design steps (algorithm) to solve the problem
• Algorithm:
– Step-by-step problem-solving process
– Solution achieved in finite amount of time
FTSM :: TK1914 20112012
24
PROBLEM SOLVING PROCESS
• Step 1 - Analyze the problem
– Outline the problem and its requirements
– Design steps (algorithm) to solve the problem
• Step 2 - Implement the algorithm
– Implement the algorithm in code
– Verify that the algorithm works
• Step 3 - Maintenance
– Use and modify the program if the problem
domain changes
FTSM :: TK1914 20112012
25
EXAMPLE 1: RECTANGLE
• Problem:
Design an algorithm to find the perimeter and
area of a rectangle.
• Information:
The perimeter and area of the rectangle are given
by the following formulas:
perimeter = 2 * (length + width)
area = length * width
FTSM :: TK1914 20112012
26
EXAMPLE 1
• Requirements:
– Input: length and width of the rectangle
– Output: perimeter and area of the rectangle
– Process: perimeter = ???, area =???
FTSM :: TK1914 20112012
27
EXAMPLE 1
• Algorithm:
– Get length of the rectangle
– Get width of the rectangle
– Find the perimeter using the following
equation:
perimeter = 2 * (length + width)
– Find the area using the following equation:
area = length * width
– Display the result perimeter and area
FTSM :: TK1914 20112012
28
EXAMPLE 2: CALCULATE CAR
PARK CHARGE
A car park has the following charges:
The 1st hour costs RM2.00. The subsequent
hours cost RM1.00 per hour. Write an algorithm
to calculate the charges based on a vehicle’s
entry and exit time.
Input
• Entry_time
• Exit_time
Process
????
FTSM :: TK1914 20112012
Output
Charge
29
EXAMPLE 2: FLOWCHART
Start
Input Entry_time
Input Exit_time
Period  Exit_time – Entry_time
Charge 2
No
Period > 1?
Yes
Charge  2 + (Period * 1)
Output
Charge
End
FTSM :: TK1914 20112012
30
EXAMPLE 2: FLOWCHART
Start
cin >> entry_time >> exit_time;
Input Entry_time
Input Exit_time
Period  Exit_time – Entry_time
Charge 2
No
Period > 1?
Yes
period = exit_time – entry_time;
Charge  2 + (Period * 1)
Output
Charge
if (period > 1)
charge = 2 + ( period *1);
else
charge = 2;
cout <<charge;
End
FTSM :: TK1914 20112012
31
EXAMPLE 2: C++ PROGRAM
void main() {
int entry_time, exit_time, period, charge;
cin >>entry_time >>exit_time;
period = exit_time – entry_time;
if
(period > 1)
charge = 2 + (period * 1);
else
charge = 2;
cout <<charge;
}
FTSM :: TK1914 20112012
32
EXAMPLE 3: PAYCHECK
• Problem:
Design an algorithm to calculate a paycheck of a
salesperson.
• Information:
– Every salesperson has a base salary.
– Salesperson receives $10 bonus at the end of
the month for each year worked if he or she
has been with the store for five or less years.
– The bonus is $20 for each year that he or she
has worked there if over 5 years.
FTSM :: TK1914 20112012
33
EXAMPLE 3
• Information (continue):
Additional bonuses are as follows:
– If total sales for the month are $5,000-$10,000,
he or she receives a 3% commission on the
sale
– If total sales for the month are at least $10,000,
he or she receives a 6% commission on the
sale
FTSM :: TK1914 20112012
34
EXAMPLE 3
• Requirements:
– Input: base salary, number of years work,
total sale
– Output: amount of paycheck (total salary)
– Process: ???
FTSM :: TK1914 20112012
35
EXAMPLE 3
• Algorithm:
– Get baseSalary
– Get noOfServiceYears
– Calculate bonus using the following formula:
if (noOfServiceYears <= 5)
bonus = 10 * noOfServiceYears
otherwise
bonus = 20 * noOfServiceYears
– Get totalSale
FTSM :: TK1914 20112012
36
EXAMPLE 3
– Calculate additionalBonus as follows:
if (totalSale < 5000)
additionalBonus = 0
otherwise
if (totalSale>=5000 and totalSale<10000)
additionalBonus = totalSale x(0.03)
otherwise
additionalBonus = totalSale x (0.06)
FTSM :: TK1914 20112012
37
EXAMPLE 3
– Calculate payCheck using the equation
payCheck = baseSalary + bonus +
additionalBonus
FTSM :: TK1914 20112012
38
EXAMPLE 4: AVERAGE TEST SCORE
• Problem:
– 10 students in a class
– Each student has taken five tests and each test
is worth 100 points.
– Design an algorithm to calculate the grade for
each student as well as the class average.
• Design an algorithm to find the average test score.
• Design an algorithm to determine the grade.
– Data consists of students’ names and their test
scores.
FTSM :: TK1914 20112012
39
EXAMPLE 4
• Algorithm 1: to find test score
– Get the five test scores.
– Add the five test scores. Suppose sum
stands for the sum of the test scores.
– Suppose average stands for the average
test score. Then
average = sum / 5;
FTSM :: TK1914 20112012
40
EXAMPLE 4
• Algorithm 2: to determine the grade.
if average > 90
grade = A
otherwise
if average >= 80 and < 90
grade = B
otherwise
if average >= 70 and < 80
grade = C
otherwise
if average >= 60 and < 70
grade = D
otherwise
grade = F
FTSM :: TK1914 20112012
41
EXAMPLE 4
• Main algorithm:
– totalAverage = 0;
– Repeat the following steps for each student in the
class.
• Get student’s name.
• Use algorithm 1.
• Use the algorithm 2.
• Update totalAverage by adding current
student’s average test score.
– Determine the class average as follows:
classAverage = totalAverage / 10
FTSM :: TK1914 20112012
42
PROGRAM STYLE AND FORM
FTSM :: TK1914 20112012
43
USE OF WHITESPACE
• Insert white space characters (such as blanks, tabs and
newlines) if necessary to increase the readability of your
source code.
Example:
int matrix[][3] = {1, 0, 0, 0, 1, 0, 0, 0, 1};
int matrix[][3] = { 1, 0, 0,
0, 1, 0,
0, 0, 1
};
• White space characters are ignored by the compiler during
compilation.
• Remember to separate reserved words and identifiers
This statement
from each other and other symbols.
is syntactically
Example:
inta, b, c;
FTSM :: TK1914 20112012
incorrect.
44
COMMAS AND SEMICOLONS
• Commas separate items in a list.
Example:
int a, b, c;
• All C++ statements end with a semicolon.
Example:
area = length * width;
• Semicolon is also called a statement terminator.
FTSM :: TK1914 20112012
45
DOCUMENTATION
• Programs are easier to read and maintain if
they are well-documented.
• Comments can be used to document code
– Single line comments begin with // anywhere in
the line
– Multiple line comments are enclosed between /*
and */
FTSM :: TK1914 20112012
46
DOCUMENTATION
• Avoid putting in useless comments such as
shown below:
int main() {
…
min = elapsed_time / 60;
sec = elapsed_time % 60;
hr = min / 60;
min = min % 60;
…
}
// assign elapsed_time / 60 to min
// assign elapsed_time % 60 to sec
// assign min / 60 to hr
// assign min % 60 to min
FTSM :: TK1914 20112012
47
DOCUMENTATION
• The program comments below are more useful:
int main() {
…
// Convert elapsed_time to min:sec
min = elapsed_time / 60;
sec = elapsed_time % 60;
// Convert min:sec to hr:min:sec
hr = min / 60;
min = min % 60;
…
}
FTSM :: TK1914 20112012
48
DOCUMENTATION
• Name identifiers with meaningful names.
• For example, which of the statements below
is more meaningful?
a = l * w;
area = length * width;
FTSM :: TK1914 20112012
49
FORM AND STYLE
• Consider two ways of declaring variables:
– Method 1
int feet, inch;
double x, y;
– Method 2
int a,b;double x,y;
• Both are correct, however, the second is hard to
read
FTSM :: TK1914 20112012
50
SYNTAX AND LOGICAL
ERROR
FTSM :: TK1914 20112012
51
SYNTAX ERRORS
• Syntax errors are errors in the source code which
are related to the syntax of the language.
• Syntax errors are detected by the compiler. An
executable file will be generated by the compiler
only if the source code it compiles has no syntax
errors.
• Syntax errors are reported by the compiler in the
form of error messages.
FTSM :: TK1914 20112012
52
#include <iostream>
using namespace std;
int main() {
cout << "This program has errors
return;
} Error messages
displayed by the
compiler
FTSM :: TK1914 20112012
53
LOGICAL ERRORS
• Logical errors are errors which are related to program
logic.
• Normally, logical errors are not detectable by the
compiler.
• Logical errors are usually detected during program
runtime. For example, a program producing
unexpected results is an indication that it has logical
errors.
• It is important to remember that if the compiler does
not produce any error messages, it does not mean
that your program is free of logical errors.
FTSM :: TK1914 20112012
54
LOGICAL ERRORS
• Possible to remove all syntax errors in a program
and still not have it run
• Even if it runs, it may still not do what you meant it
to do
• For example,
2 + 3 * 5 and (2 + 3) * 5
are both syntactically correct expressions, but
have different meanings
FTSM :: TK1914 20112012
55
 Write a program to calculate
the area of the region in
blue.
#include <iostream>
using namespace std;
int main() {
float radius, length, width;
cout << "Enter radius, length and width: ";
cin >> radius >> length >> width;
cout << "Area of blue region: " << length * width 3.14*radius*radius;
return 0;
}
FTSM :: TK1914 20112012
56

Suppose we test the program with these
inputs:
radius: 7
length: 2
width: 3
Area of circle = 3.14 * 7 * 7 = 153.86
Area of rectangle = 2 * 3 = 6

This means that the rectangle is enclosed by
the circle. The area of the region should not
be negative.
FTSM :: TK1914 20112012
57
• The following output is generated when the
program is executed with those inputs.
• The program should be checked for logical
errors.
FTSM :: TK1914 20112012
58
#include <iostream>
using namespace std;
int main() {
float radius, length, width;
cout << "Enter radius, length and width: ";
cin >> radius >> length >> width;
cout << "Area of blue region: "
<< length*width - 3.14*radius*radius;
return 0;
}
The formula should be
3.14*radius*radius – length*width
FTSM :: TK1914 20112012
59
YOU SHOULD NOW KNOW…
• what an algorithm is.
• when an algorithm should be developed when
building a computer program.
• the basic steps in building a computer program
to solve a problem.
• what flowcharts are.
• how to represent algorithms graphically using
flowcharts.
FTSM :: TK1914 20112012
60
YOU SHOULD NOW KNOW…
• importance of program readability
– using whitespace characters
– inserting comments
– using meaningful names for identifiers
• syntax and logical errors
FTSM :: TK1914 20112012
61