Title: Algorithms and Problem Solving
1TK 1914 C Programming
- Algorithms and Problem Solving
2WHAT 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.
3Algorithm in Real Life
- Consider the following
- Problem Baking a Cake
- How to solve
- Start
- Preheat the oven at 180oC
- Prepare a baking pan
- Beat butter with sugar
- Mix them with flour, eggs and essence vanilla
- Pour the dough into the baking pan
- Put the pan into the oven
- End
4Divide and Conquer Strategy in Algorithm
- Problem Prepare a Breakfast
-
1. Start 2. Prepare a Breakfast 3. End
5Divide 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
6Divide 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
7Divide 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
8Divide 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
9CLASS ACTIVITY 5.1
- Write a simple algorithm for withdrawing a sum of
money at an ATM.
10WHY 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.
11ALGORITHMS 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.
12- 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.
13HOW 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
14FLOWCHARTS
- A flowchart is a graphical representation of the
sequence of operations in a program. - An algorithm can be represented graphically using
a flowchart.
15Flowchart notations
16FLOWCHART EXAMPLE 1
Start
Input Gregorian date
Convert Gregorian date to Islamic date
Display Islamic date
End
17Pseudocode
- 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
18Example of Pseudocode
- 1. Start
- 2. Read quantity
- 3. Read price_per_kg
- 4. price ? quantity price_per_kg
- 5. Print price
- 6. End
19CLASS ACTIVITY 5.2
- Draw a flowchart which represents the algorithm
built in CA5.1.
20FLOWCHART EXAMPLE 2
Start
- length, width and area are referred to as
variables. - A variable is like a box in which a value can be
stored
Input length, width
area ? length X width
Output area
End
21FLOWCHART EXAMPLE 3
Start
Input height
false
true
height gt 1.6?
Output You are short!
Output You are tall!
End
22FLOWCHART EXAMPLE 4
Start
Output Thank you!
Input stop
false
true
End
23Problem solving
24Problem 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
25Problem 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
26Example 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
27Example 1
- Requirements
- Input length and width of the rectangle
- Output perimeter and area of the rectangle
- Process perimeter ???, area ???
28Example 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
29Example 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 vehicles entry and exit
time.
Process
Input
Output
Charge
????
30Example 2 Flowchart
31Example 2 Flowchart
cin gtgt entry_time gtgt exit_time
period exit_time entry_time
if (period gt 1) charge 2 ( period
1) else charge 2 cout ltltcharge
32Example 2 C Program
void main() int entry_time, exit_time, period,
charge cin gtgtentry_time gtgtexit_time period
exit_time entry_time if (period gt
1) charge 2 (period 1) else charge
2 cout ltltcharge
33Example 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.
34Example 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
35Example 3
- Requirements
- Input base salary, number of years work, total
sale - Output amount of paycheck (total salary)
- Process ???
36Example 3
- Algorithm
- Get baseSalary
- Get noOfServiceYears
- Calculate bonus using the following formula
- if (noOfServiceYears lt 5)
- bonus 10 noOfServiceYears
- otherwise
- bonus 20 noOfServiceYears
- Get totalSale
37Example 3
- Calculate additionalBonus as follows
- if (totalSale lt 5000)
- additionalBonus 0
- otherwise
- if (totalSalegt5000 and totalSalelt10000)
- additionalBonus totalSale x(0.03)
- otherwise
- additionalBonus totalSale x (0.06)
38Example 3
- Calculate payCheck using the equation
- payCheck baseSalary bonus
additionalBonus
39Example 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.
40Example 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
41Example 4
- Algorithm 2 to determine the grade.
- if average gt 90
- grade A
- otherwise
- if average gt 80 and lt 90
- grade B
- otherwise
- if average gt 70 and lt 80
- grade C
- otherwise
- if average gt 60 and lt 70
- grade D
- otherwise
- grade F
42Example 4
- Main algorithm
- totalAverage 0
- Repeat the following steps for each student in
the class. - Get students name.
- Use algorithm 1.
- Use the algorithm 2.
- Update totalAverage by adding current students
average test score. - Determine the class average as follows
- classAverage totalAverage / 10
43Program style and Form
44USE OF WHITESPACE
- Insert white space characters (such as blanks,
tabs and newlines) if necessary to increase the
readability of your source code. - Example
- int matrix3 1, 0, 0, 0, 1, 0, 0, 0, 1
- int matrix3 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 from each other and other symbols. - Example inta, b, c
45COMMAS 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.
46DOCUMENTATION
- 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 /
47DOCUMENTATION
- Avoid putting in useless comments such as shown
below
int main() min elapsed_time / 60 //
assign elapsed_time / 60 to min sec
elapsed_time 60 // assign elapsed_time 60 to
sec hr min / 60 // assign min / 60 to
hr min min 60 // assign min 60 to
min
48DOCUMENTATION
- The program comments below are more useful
int main() // Convert elapsed_time to
minsec min elapsed_time / 60 sec
elapsed_time 60 // Convert minsec to
hrminsec hr min / 60 min min 60
49DOCUMENTATION
- Name identifiers with meaningful names.
- For example, which of the statements below is
more meaningful? - a l w
- area length width
50Form and Style
- Consider two ways of declaring variables
- Method 1
- int feet, inch
- double x, y
- Method 2
- int a,bdouble x,y
- Both are correct, however, the second is hard to
read
51Syntax and logical error
52SYNTAX 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.
53include ltiostreamgt using namespace std int
main() cout ltlt "This program has
errors return
54LOGICAL 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.
55LOGICAL 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
56- Write a program to calculate the area of the
region in blue.
include ltiostreamgt using namespace std int
main() float radius, length, width cout ltlt
"Enter radius, length and width " cin gtgt
radius gtgt length gtgt width cout ltlt "Area of blue
region " ltlt length width - 3.14radiusradius
return 0
57- 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.
58- The following output is generated when the
program is executed with those inputs. - The program should be checked for logical errors.
59include ltiostreamgt using namespace std int
main() float radius, length, width cout ltlt
"Enter radius, length and width " cin gtgt
radius gtgt length gtgt width cout ltlt "Area of
blue region " ltlt lengthwidth -
3.14radiusradius return 0
60YOU 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.
61YOU SHOULD NOW KNOW
- importance of program readability
- using whitespace characters
- inserting comments
- using meaningful names for identifiers
- syntax and logical errors