610 likes | 620 Views
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.
E N D
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
Algorithm 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 FTSM :: TK1914 20112012
‘Divide and Conquer’ Strategy in Algorithm Problem: Prepare a Breakfast 1. Start 2. Prepare a Breakfast 3. End FTSM :: TK1914 20112012
‘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
‘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
‘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
‘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
CLASS ACTIVITY 5.1 • Write a simple algorithm for withdrawing a sum of money at an ATM. FTSM :: TK1914 20112012
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
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
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
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
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
Semantic Symbol Start/End Process Input/Output Test Connector Flow of activities Flowchart notations FTSM :: TK1914 20112012
Algorithm starts here Input data from user Perform the date conversion Display the result Algorithm ends here FLOWCHART: EXAMPLE 1 Start Input Gregorian date Convert Gregorian date to Islamic date Display Islamic date End FTSM :: TK1914 20112012
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
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
CLASS ACTIVITY 5.2 • Draw a flowchart which represents the algorithm built in CA[5.1]. FTSM :: TK1914 20112012
FLOWCHART: 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 FTSM :: TK1914 20112012
FLOWCHART: EXAMPLE 3 • Selection Start Input height false true height > 1.6? Output “You are short!” Output “You are tall!” End FTSM :: TK1914 20112012
stop = 1? FLOWCHART: EXAMPLE 4 • Repetition (looping) Start Output “Thank you!” Input stop false true End FTSM :: TK1914 20112012
Problem solving FTSM :: TK1914 20112012
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
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
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
Example 1 • Requirements: • Input: length and width of the rectangle • Output: perimeter and area of the rectangle • Process: perimeter = ???, area =??? FTSM :: TK1914 20112012
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
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. Process Input Output • Entry_time • Exit_time ???? Charge FTSM :: TK1914 20112012
No Yes Example 2: Flowchart Start Input Entry_time Input Exit_time Period Exit_time – Entry_time Period > 1? Charge 2 Charge 2 + (Period * 1) Output Charge End FTSM :: TK1914 20112012
No Yes Example 2: Flowchart cin >> entry_time >> exit_time; Start Input Entry_time Input Exit_time period = exit_time – entry_time; Period Exit_time – Entry_time Period > 1? Charge 2 Charge 2 + (Period * 1) if (period > 1) charge = 2 + ( period *1); else charge = 2; cout <<charge; Output Charge End FTSM :: TK1914 20112012
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
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
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
Example 3 • Requirements: • Input: base salary, number of years work, total sale • Output: amount of paycheck (total salary) • Process: ??? FTSM :: TK1914 20112012
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
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
Example 3 • Calculate payCheck using the equation payCheck = baseSalary + bonus + additionalBonus FTSM :: TK1914 20112012
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
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
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
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
Program style and Form FTSM :: TK1914 20112012
This statement is syntactically incorrect. 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 from each other and other symbols. Example: inta, b, c; FTSM :: TK1914 20112012
COMMAS AND SEMICOLONS • Commas separate items in a list. Example: inta, b, c; • All C++ statements end with a semicolon. Example: area = length * width; • Semicolon is also called a statement terminator. FTSM :: TK1914 20112012
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
DOCUMENTATION • 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 … } FTSM :: TK1914 20112012
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
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
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