Algorithms Problem Solving Prepared by mazhar Javed Topic
Algorithms Problem Solving Prepared by : mazhar Javed
Topic & Structure of the lesson Design In this chapter you will learn about: • Problem Solving • Algorithm • Pseudocodes • Flowcharts PSPD Using C 2
Key Terms you must be able to use Design If you have mastered this topic, you should be able to use the following terms correctly in your assignments and exams: • program • pseudocode • flowchart • algorithm PSPD Using C 3
Problem Solving Techniques Design In this chapter you will learn about: § What problem solving is § The software development method of problem solving using computers § Basic algorithm control structures The sequence structure The selection structure The repetition structure PSPD Using C 4
Problem Solving Techniques Design By the time you have completed this chapter, you will have acquired the ability to: § Apply the software development method to solve problems § Difference between the Algorithm & the Flowchart § Knowing about the control structures PSPD Using C 5
Problem Solving Design UNDERSTANDING THE PROBLEM First: What is the unknown? What are the data? What is the condition? You have to understand the Is it possible to satisfy the condition? Is the condition sufficient to determine the unknown? Or problem. is it sufficient? Or Redundant? Or Contradictory? Draw a figure. Introduce suitable notation. Separate the various parts of the condition. Can you write them down? PSPD Using C 6
Problem Solving Design Seco nd: Find the connection between the data and the unknown. Auxiliary problems may be devised if needed. You should obtain eventually a plan of the solution. PSPD Using C DEVISING A PLAN Have you seen it before? Or have you seen the same problem in slightly different form? Do you know a related problem? Look at the unknown! Try to think of a familiar problem having the same or similar unknown. Split the problem into smaller, simple sub-problems. If you cannot solve the proposed problem try to solve first some related problem. Or solve more general problem. Or special case of the problem. Or solve the part of the problem. 7
Problem Solving Design Third: CARRYING OUT THE PLAN Carry out your plan. Carrying out your plan of the solution, check each step. Can you see clearly that step is correct? Can you prove that it is correct? Fourth: LOOKING BACK Examine the Can you check the result? Can you derive solution obtained. the result differently? Can you use the result, or the method, for some other problem? PSPD Using C 8
Problem Solving Design The software development method consists of the following steps: Requirements specification Analysis Design Implementation Testing and verification Documentation PSPD Using C 9
Algorithmic Problem Solving Design Algorithmic problem: Any problem whose solution can be expressed as a set of executable instructions. Algorithm: 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. PSPD Using C 10
Algorithmic Problem Solving Design Derived from the name of Mohammed alkhowarizmi, a Persian mathematician in the ninth century. Al-khowarizmi--Algorismus(in Latin)--Algorithm § An algorithm is like a recipe, that converts the ingredients into some culinary dish. § The formal written version is a program. § Algorithms/programs are the software. The machine that runs the programs is the hardware. PSPD Using C 11
Algorithmic Problem Solving Design Ingredient Recipe (software) Cooking utensils (hardware) Al-gong Bah-kut-the PSPD Using C 12
Characteristics of an Algorithm Design § Each step of an algorithm must be exact, preciously and ambiguously described. § It must terminate, i. e. it contains a finite number of steps. § It must be effective, i. e. . , produce the correct output. § It must be general, i. e. . to solve every instance of the problem. PSPD Using C 13
Characteristics of an Algorithm Design § An Algorithm is implemented in some programming language. program = Algorithm + Data Structures. § Data Structures refer to the types of data used and how the data are organized in the program. § An algorithm is usually presented in the form of some pseudo-code, which is a mixture of English statement, some mathematical notations, and selected keywords from a programming language. PSPD Using C 14
Characteristics of an Algorithm Design § An Algorithm should emphasize the WHAT’s and not the HOW’s. Consider the problem below: PROBLEM: You are required to design a complete system which will enable the sum of two values to be calculated. PSPD Using C 15
Problem Solving Design To grapple with this problem, we have to understand the problem from the human perspective. A question to ask yourself is this, “How Would You Calculate the Sum of Two Values? ” PSPD Using C 16
Problem Solving Design As the computer is also a device similar to the way in which the human brain functions, the process of calculating the sum of two values can also be easily performed by the computer. = PSPD Using C 17
Problem Solving Design Processing (Brains) Input Output PSPD Using C 18
Problem Solving Output Device Design CPU (Brains) Input Device PSPD Using C 19
Problem Solving Design Processing 10 5 5 + 10 = 15 15 Input Output Let us assume we are interested in calculating the sum of 5 and 10. PSPD Using C 20
Problem Solving Design As shown previously, the example values (5 and 10) have been specified explicitly. As the brain is flexible enough in calculating a wide range of numbers, the two input values have to be generalised. PSPD Using C 21
Problem Solving Design Value 2 Value 1 Sum = Value 1 + Value 2 Sum Notice that instead of using specific numbers, variables are used to represent these values. PSPD Using C 22
What Are Variables? Design Variables are memory locations within the computer which allows pieces of data to be stored. The word variable comes from the word vary, which means that whatever you place within a variable can be changed. A variable can be viewed as a container used to store things. Data (for example, name, age, salary) can be stored in these containers. PSPD Using C 23
What Are Variables? Design PSPD Using C 24
Problem Solving Design Now that we have an exact idea about how the problem is solved, let us represent this in a clearer manner, using the defining diagram. Input Value 1 Processing Output Sum Value 2 PSPD Using C 25
Problem Solving Design The next step is to identify the actual processing steps required to convert the input to become the output. Input Processing Value 1 1) Read Value 1, Value 2 2) Calculate Sum Output Sum 3) Display Sum PSPD Using C 26
Algorithm Development Once the defining diagram has been developed, the next logical step is to develop the algorithm (which is much more detailed). Input Processing Value 1 1) Read Value 1, Value 2 2) Calculate Sum Design Output Sum 3) Display Sum The developed processing steps have to be more detailed in the algorithm. PSPD Using C 27
Algorithm Development Design The basic mathematical operators used in algorithms are as follows: - PSPD Using C + addition - subtraction * multiplication / division = assignment () brackets for grouping calculations 28
Algorithm Development Design Example of an algorithm (using pseudocodes) which can be used to carry out the tasks outlined in the defining diagram is as follows: 1) Read Value 1, Value 2 2) Calculate Sum = Value 1 + Value 2 3) PSPD Using C Display Sum 29
Pseudocoding Design A Pseudocode language is semiformal, Englishlike language with a limited vocabulary that can be used to design and describe algorithms. The pseudocode language can be used for: § Designing algorithms § Communicating algorithms as programs § Implementing algorithms as programs § Debugging logic errors in program PSPD Using C 30
Pseudocode for the Control Structures Design The Sequence Control Structure: The sequence control structure is a series of steps or statements that are executed in the order in which they are written in an algorithm. For Example: read taxable income read filing status compute income tax PSPD Using C 31
Cont’d Design The Selection Control Structure: The selection control structure defines two courses of action, depending on the outcome of a condition. A condition is an expression that, when evaluated, computes to either true or false. Syntax is: if condition then-part else-part end-if PSPD Using C 32
Decision Making Design Being able to mimic the way the human brain works, the computer also has the ability to make decisions. Decision making can be represented in pseudocodes using the IF. . . THEN construct. IF (expression) THEN : : ENDIF PSPD Using C 33
Decision Making Design The expression is a comparison between two values which evaluates to either true of false. IF (expression) THEN : : ENDIF Statements are placed here. PSPD Using C 34
Decision Making Design Example: We are looking for a job which pays more than RM 4000. Example of an Expression IF (Salary>4000) THEN Say "I Will Take The Job!!" ENDIF PSPD Using C 35
Decision Making Design Commonly used relational operators in expressions: > Greater Than < Less Than = Equals To <> Not Equals To >= Greater Than or Equals To <= Less Than or Equals To () Brackets used for prioritising certain calculations PSPD Using C 36
Decision Making Design Since all expressions works out to be either true or false, what the IF. . THEN statement represents is a two-state condition. For example, A potential employer is waiting for you to give a reply (on the spot) about the job offer with a salary of RM 2000. Your decision would be to only take a job worth more than RM 4000. What would you say? IF (Salary>4000) THEN Say “YES!” ELSE Say “NO!” ENDIF PSPD Using C 37
Decision Making Design Certain conditions may give rise to more than one expression being evaluated. These are known as compound expressions. Example: You are interested in taking up a job which pays more than RM 4000 and that the company must also provide a credit card. IF (Salary>4000) And (Credit. Card=YES) THEN Take Job!! ENDIF PSPD Using C 38
Decision Making Design Compound expressions can be represented using the following operators: AND Every expression must evaluate to be true in order for the whole expression to be true. OR As long as any one of the expression can be true, the entire IF statement will be true. NOT The inverse (opposite) of the entire expression. PSPD Using C 39
Decision Making Design IF statements can be nested, that is, placed within another IF statement. This is used in situations when the expression is more complex than the simple decisions (as seen earlier). PSPD Using C 40
Decision Making For example, this statement. . Design IF (Salary>4000) And (Credit. Card=YES) THEN Say “Yes I Will Take The Job!!” ENDIF can be represented like this. . IF (Salary>4000) THEN IF (Credit. Card=YES) THEN Say “Yes I Will Take The Job!!” ELSE Say “No Credit Card? ” Say “Sorry!!” ENDIF ELSE Say “Not Enough Pay!!” ENDIF . . . . whereby more possibilities can be represented. PSPD Using C 41
Decision Making For good practice. . . Design IF (Salary>4000) THEN IF (Credit. Card=YES) THEN Say “Yes I Will Take The Job!!” ELSE Say “No Credit Card? ” Say “Sorry!!” ENDIF ELSE Say “Not Enough Pay!!” ENDIF . . . . ensure that statements are properly indented to indicate block of statements which belong together. PSPD Using C 42
Cont’d Design For Example: if a is greater than b then print “A is greater” else print “B is greater” end if PSPD Using C 43
Cont’d Design Repetition Control Structure: The repetition control structure specifies a block of one or more statements that are repeatedly executed until a condition is satisfied. Syntax is: while condition loop-body end-while PSPD Using C 44
Looping Constructs Design Looping constructs (also known as repetition or iteration constructs) are a kind of construct found in pseudocodes which allows statements (or a group of statements) to be repeated. The main reason why looping constructs are provided is because most of the problems which we encounter everyday requires some degree of repetition. PSPD Using C 45
Looping Constructs Design An example of a process which is iterative: - Payroll processing is very much an iterative process as the person processing the payroll applies the same calculations for each employee to produce the pay slip. PSPD Using C 46
Looping Constructs Design The looping constructs available in pseudocodes are as follows: DOWHILE. . . ENDDO FOR…NEXT REPEAT. . . UNTIL PSPD Using C 47
Looping Constructs Design The format of the DOWHILE. . . ENDDO construct is shown below: DOWHILE (expression) : : : ENDDO Group of statements PSPD Using C An expression which determines whether the loop will continue. 48
Looping Constructs Design The format of the FOR. . . NEXT construct is shown below: FOR (initialze TO expression) STEP increment : : : ENDDO Group of statements PSPD Using C An expression which determines whether the loop will continue. 49
Looping Constructs Design The format of the REPEAT. . . UNTIL construct is shown below: REPEAT : : : UNTIL (expression) Group of statements PSPD Using C An expression which determines whether the loop will continue. 50
Looping Constructs Design Take a look at the following example: You are required to develop a complete system which will allow the total payroll to be calculated. The system is required to read in the amount to be paid for each employee. The moment the system receives an input value of -99, the system is required to stop and display the total payroll. PSPD Using C 51
Looping Constructs Design The Defining Diagram Input Salary Processing 1) Read Salary Output Total 2) Calculate Total 3) Display Total PSPD Using C 52
Looping Constructs Algorithm (Using Pseudocodes) Design 1) Display "Enter Salary" 2) Read Salary 3) Total = 0 4) DOWHILE (Salary<>-99) Total = Total + Salary Display "Enter Salary" Read Salary ENDDO 5) Display "Total Payroll = ", Total PSPD Using C 53
Cont’d Design Example: Dowhile (income is less than 50000) print “Enter taxable income; should be greater than or equal to 50000” read income Enddo PSPD Using C 54
Desk Check Table Design A desk check table is used to verify the correctness of the design. This is to ensure that the program which will eventually be developed is going to produce the answer which is required. The desk check table is developed based on the following steps: 1) 2) 3) 4) PSPD Using C Identify the data sets. Identify the expected results. Trace through the algorithm with the data sets using a trace table. Analyse & compare the results produced in step (3) and the expected results in step (2). 55
Desk Check Table Identify Data Sets Input Processing Value 1 1) Read Value 1, Value 2 2) Calculate Sum Design Output Sum 3) Display Sum Focus on the input section of the defining diagram and identify some possible values (data sets) which can be used to test the system. PSPD Using C 56
Desk Check Table Design Identify Expected Results Input Processing Value 1 1) Read Value 1, Value 2 2) Calculate Sum Output Sum 3) Display Sum Focus on the output section of the defining diagram and identify some possible values which the system will produce based on the data sets. PSPD Using C 57
Desk Check Table Design Trace Table - Data Set 1 Value 1 Read 5 Value 2 Sum 3 Calculate 8 Display Do the results match the expected results? PSPD Using C 58
Desk Check Table Design Trace Table - Data Set 2 Value 1 Read 8 Value 2 Sum 13 Calculate 21 Display Do the results match the expected results? PSPD Using C 59
Desk Check Table Design Trace Table - Data Set 3 Value 1 Read 15 Value 2 Sum 9 Calculate 24 Display Do the results match the expected results? PSPD Using C 60
Program Flowcharts Design As humans are more inclined towards understanding diagrams and pictures rather than words, pseudocodes tends to become tedious to understand if too lengthy. Program flowcharts, because they are represented graphically, makes understanding easier. PSPD Using C 61
Program Flowcharts The following are the commonly used symbols for drawing program flowcharts. Design terminator off-page connector process storage decision making document input/output connector arrowheads PSPD Using C 62
Program Flowcharts Begin Design Read Value 1, Value 2 Calculate Sum = Value 1 + Value 2 Display Sum End PSPD Using C 63
Program Flowcharts Begin Design Read Amount YES Amount>20. 00? Calculate Actual=Amount * 0. 80 NO Calculate Actual=Amount End PSPD Using C 64
Flowcharting Design § Another technique used in designing and representing algorithms. § Alternative to pseudocoing § A pseudocode description is verbal, a flowchart is graphical in nature. Definition: § A flowchart is a graph consisting of geometrical shapes that are connected by flow lines. PSPD Using C 65
Sequence Structure Design Pseudocode: statement_1 Flowchart: Statement -1 statement_2 ------ Statement -2 statement_n Statement -n PSPD Using C 66
Selection Structure Design Pseudocode: Flowchart: if condition then-part else false else-part condition true end_if else-part PSPD Using C then-part 67
Selection Structure Design Pseudocode: Flowchart: if condition Y then-part end_if condition N false PSPD Using C true then-part 68
Repetition Structure Design Pseudocode: Flowchart: while condition loop-body T end-while condition Y loop-body F N PSPD Using C 69
Summary Design § Problem Solving– the process of transforming the § § PSPD Using C description of a problem to its solution. To Solve complex problems, we use computers as a tool and develop computer programs that give us solutions. A commonly used method for problem solving using computers is the software development method, which consists of six steps. 70
Summary Design 1. The Requirements specification, provides us with a precise definition of the problem. PSPD Using C 2. In the analysis phase we identify problem inputs, outputs, special constraints, and formulas and equations to be used. 3. The design phase is concerned with developing an algorithm for the solution of the problem. 71
Summary Design 4. The implementation of an algorithm is a computer program. When executed, it should produce the solution to the problem. 5. Program Verification is the process of ensuring that a program meets user requirements. 6. Program testing, on the other hand, is the process of executing a program to demonstrate its correctness. 7. Program Documentation facilitates the use of the program, future program maintenance efforts, and program debugging. PSPD Using C 72
Summary Design § An algorithm is a sequence of a finite number of steps arranged in a specific logical order that, when executed, produce the solution for a problem. § A pseudocode language is a semiformal, English-like language with a limited vocabulary that can be used to design and describe algorithms. PSPD Using C 73
Summary Design § Any algorithm can be described in terms of three basic control structures. They are the sequence, selection and repetition structures. § The top-down stepwise refinement of algorithms is a fundamental problem-solving strategy. § A Flowchart is a graphical representation of an algorithm. PSPD Using C 74
Quick Review Question Design 1. State the difference between the Dowhile – Enddo structure and the Repeat – Until structure. 2. Write an algorithm that will display the first hundred even numbers 3. using the Do-While loop. PSPD Using C 75
Follow Up Assignment Design • This is an individual piece of work. • Your source code will be discussed at the end of the next lesson. PSPD Using C 76
Summary of Main Teaching Points Design • Problem Solving • Pseudocodes • Flowcharts • Basic control structures • The sequence structure • The selection structure • The repetition structure PSPD Using C 77
- Slides: 77