Algorithms and Problem Solving 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
Flowchart notations Semantic Symbol Start/End Process Input/Output Test Connector Flow of activities FTSM :: TK1914 20112012
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 End Algorithm ends here 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 Output “You are short!” Output “You are tall!” End FTSM :: TK1914 20112012
FLOWCHART: EXAMPLE 4 Repetition (looping) Start Output “Thank you!” Input stop stop = 1? 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. Input Process Output Entry_time Exit_time ???? Charge FTSM :: TK1914 20112012
Period Exit_time – Entry_time Example 2: Flowchart Input Entry_time Input Exit_time Start Output Charge End Period Exit_time – Entry_time Period > 1? Yes Charge 2 + (Period * 1) Charge 2 No FTSM :: TK1914 20112012
Period Exit_time – Entry_time Example 2: Flowchart Input Entry_time Input Exit_time Start Output Charge End Period Exit_time – Entry_time Period > 1? Yes Charge 2 + (Period * 1) Charge 2 No 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 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: Information: 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) 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 average = sum / 5; 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 if average >= 70 and < 80 grade = C if average >= 60 and < 70 grade = D 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
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; This statement is syntactically incorrect. FTSM :: TK1914 20112012
Example: area = length * width; 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
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
Syntax and logical error FTSM :: TK1914 20112012
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
#include <iostream> using namespace std; int main() { cout << "This program has errors return; } Error messages displayed by the compiler FTSM :: TK1914 20112012
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
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
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; } Example of logical error FTSM :: TK1914 20112012
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
The program should be checked for logical errors. The following output is generated when the program is executed with those inputs. The program should be checked for logical errors. FTSM :: TK1914 20112012
#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; } Example of logical error The formula should be 3.14*radius*radius – length*width FTSM :: TK1914 20112012
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
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