Introduction to Programming - TMF 1414 Lecture Notes PDF

Summary

This document provides lecture notes about problem-solving strategies and algorithms, including examples and pseudocode used to solve programming tasks.

Full Transcript

TMF 1414 Introduction to Programming Lecture 02: Problem Solving & Algorithms 1 We will learn about: What is Problem Solving? How to solve a problem? Problem Solving Strategies Solving problem with computer Software Development Metho...

TMF 1414 Introduction to Programming Lecture 02: Problem Solving & Algorithms 1 We will learn about: What is Problem Solving? How to solve a problem? Problem Solving Strategies Solving problem with computer Software Development Method of Problem Solving Steps in the Software Development Method Design & representation of algorithms Programming errors & debugging Program verification & testing Flowchart & Pseudocode 2 What Definition: is Problem Solving? Problem solving is the process of transforming the description of a problem into the solution of that problem by using our knowledge of the problem domain and by relying on our ability to select and use appropriate problem solving strategies, techniques and 3 tools. People make decisions everyday Examples: ⮚ Should I wear casual or formal today? Problem ⮚ Should I watch TV or go out to cinema? Faced in ⮚ Where is my c programming Everyda lab? ⮚ What is the course code? y in Life ⮚ Where to put my bag? ⮚ Everything needs a DECISION AS A SOLUTION TO THE PROBLEM 4 Steps to solve a problem Step 1: Identify the problem Step 2: Determine the problem solving strategy to apply Step 3: Design the solution Step 4: Execute the solution Step 5: Evaluate the successfulness of the solution 5 Many strategies can be use in solving problem. Most popular type of strategy is the “Art of War” by Sung Zhi (Ancient Chinese Philosopher) We will learn: Problem Guess and Check (Try an Error) Solving Strategie Start at the end (Work Backward) Divide and Conquer s Look for a Pattern 6 Guess and Check (Try an Error) Simplest strategy available. Just experimenting with the possible solution. A bit time consuming if have a lot of possible solution Problem Solving But it is very efficient and practical for solving small or medium problem Strategie Example s Prince A divided 15 stone games into two piles: games he owns and games his brother owns. He owns 3 more games than his brother. How many games does his brother own? 7 Solution I'll guess his brother owns 8 games. That means Prince A owns 11 games. That's a total of 19 games. My guess is too high. I'll guess again. This time I'll guess his brother owns 6 games. That means Prince A owns 9 games. That's a total of 15 games. My guess is right. His brother owns 6 games. Guess and Check (Try an Error) 8 Start at The End (Working Backward) Sometime to solve some problem, you may need to undo some of the key actions in the problem. Also known as bottom-up approach Example: The castle kitchen servants brought in 4 pies left over from the feast. 12 pies were eaten at the feast. Queen Mab took 2 home with her. How many pies did the servants bring into the feast at the beginning? 9 Solution First, I'll account for all the pies that were eaten or taken home. 12 + 2 = 14 Then I'll add the 4 pies that were left over. 14 + 4 + 18 Therefore, there must have been 18 pies at the start of the feast. Start at The End (Working Backward) 10 Divide and Conquer Most popular strategy used in problem solving. Used by Napoleon in his quest to conquer the world. Often break up large problems into smaller units that are easier to handle. 11 Divide and Conquer 12 Look for a pattern More advance way to solve a complicated problem Some problem can be solved by recognizing pattern within the domain. For example: Daniel arranged loaves of bread on 6 shelves in the bakery. He put 1 loaf on the top shelf, 3 loaves on the second shelf, and 5 loaves on the third shelf. If he continues this pattern, how many loaves did Daniel put on the 6th shelf? 13 Solution Shelf 1 2 3 4 5 6 Loaves 1 3 5 7 9 11 Look for a pattern 14 Other Strategies 🟂 Drawings/modeling 🟂 Logical Reasoning 🟂 Extra Information TIPs: Strategy is only to help you to solve problem. Most important thing is to keep your mind cool and try to find ways to overcome the difficulties!! 15 Computers use algorithmic solutions: Program – set of instructions that make up solution to a problem Results – outcome of running Solving the program Problem Testing – Are the outcomes with what we expected and correct Computer Documentation manual documentation – instructions telling users how to use the program 16 Clearly define the problem. Problem Analyse the problem and solving formulate a method to solve it. with Describe the solution in the form of an algorithm. compute Draw a flowchart of the rs algorithm. involves Write the computer program. several Compile and run the program (debugging). steps Test the program (debugging) (see also verification.). Interpretation of results. 17 Thus, we use software development method which consists of the following steps: Requirement specification Analysis Design Implementation Testing and verification Documentation 18 Solving a Problem vs Developing a program Steps to solve problem Software Development Method Step 1: Identify the problem Step 1: Requirement specification Step 2: Identify the possible Step 2: Analysis solution and determine the best applicable solution Step 3: Design the solution Step 3: Design Step 4: Execute the solution Step 4: Implementation Step 5: Evaluate the Step 5: Testing and verification successfulness of the solution Step 6: Documentation 19 Requirement Analysis Specification Basic Steps in Implementati Software/Applica Design on & Deployment tion Development Documentati Testing on 20 Requirement Specification A task to determine the needs and conditions (including scope) to meet in the new system Requirements can be obtained through several methods Brainstorming session Survey Interview Observation others 21 Analysis After obtaining the requirements, then the software developer need to study the approach/ method to solve the problem. Using different problem techniques Determine best solution from given options 22 Design A crucial phase before the actual coding process Several thing need to be consider during the design of a application or software Compatibility Extensibility Reliability Reusability Robustness Usability 23 Design Designing software usually is designing an Algorithm. An Algorithm is a sequence of a finite number of steps arranged in a specific logical order, which, when executed, produce the solution for a problem. 24 An algorithm must satisfy some requirements: – Unambiguousness – It must not be ambiguous. – Computers cannot cope with ambiguous. Design – Therefore, every step in an algorithm must be clear as to what it is supposed to do and how many times it is expected to be executed. 25 – Generality – It must have generality. – A procedure that prints the message “One inch is 2.54 cm” is not an algorithm; Design – however, one that converts a supplied number of inches to centimeters is an algorithm. 26 – Correctness – It must be correct and must solve the problem for which it is designed. – Finiteness Design It must execute its steps and terminate in finite time. An algorithm that never terminates is unacceptable. 27 A specific and step-by-step set of instructions for carrying out a procedure or solving a problem, usually with the requirement that the procedure terminate at Algorith some point Pseudocode m 2 types of algorithm representation will be explained: Flowchart Pseudocode 28 a semiformal, English-like language (or other language that can be understand by human being) limited vocabulary that can be used to design Pseudocode and describe algorithms. Not executed on computers A carefully prepared pseudocode program may be converted easily to a corresponding C program 29 Designing algorithms Communicating algorithms to users Implementing algorithms as programs Debugging logic errors in program Documenting programs for future maintenance and expansion purposes Pseudoco de A pseudocode must meet these requirements: Have a limited vocabulary Be easy to learn Produce simple, English-like narrative notation 30 Be capable of describing all An algorithm can be How to written in pseudocode using six (6) basic write computer operations: Pseudoco Pseudoc ▪ Receive de ▪ Output ode ▪ Arithmetic operation ▪ Assign ▪ Compare ▪ Repeat 31 How to write Pseudocode A computer can receive information. Typical pseudocode instructions to receive information are: Read name Get name Read number1, number2 32 How to write A computer Pseudocode can output (print) information. Typical pseudocode instructions are: Print name Write "The average is", ave A computer can perform arithmetic operation Typical pseudocode instructions: Add number to total 33 Total = Total + Number How to write Pseudocode How to write Pseudocode A computer can assign a value to a piece of data: To assign/give data an initial value: Initialize total to zero Set count to 0 To assign a computed value: Total = Price + Tax 34 How to write Pseudocode How to write A computer Pseudocode can compare two pieces of information and select one of two alternative actions. Typical pseudocode e.g. If number < 0 then add 1 to neg_number else add 1 to pos_number end-if 35 How to write Pseudocode A computer can repeat a group of How actions to write Pseudocode Typical pseudocode e.g. Repeat until total = 50 read number write number add 1 to total end-repeat OR while total < = 50 do: read number write number 36 Start Read status if status is equal to 1 Another print “on” Example else If of status is equal to 0 pseudoco print “ Off” else de print “Error in status code” end_if end 37 Algorithm in Real-life Actually, our daily life /routine also can be written using a pseudocode Consider the following real-life case on baking a cake. How to write it in a proper pseudocode? 38 Baking a Cake (pseudocode) 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 39 Algorithm in Real-life Let’s see how to write a simple pseudocode on how to prepare a breakfast 40 Algorithm in Real-life Some of you may write this simple answer Start Prepare the breakfast End 41 Algorithm in Real-life 1.Start 2. Prepare a Breakfast 2.1. Prepare a tuna sandwich 2.1.1 Take 2 slices of bread OR some of 2.1.2 Prepare tuna paste you may 2.2. Prepare some chips write the 2.2.1 Cut potatoes into slices pseudocode 2.2.2 Fry the potatoes in more 2.3. Make a cup of coffee detail on 2.3.1 Boil water 2.3.2 Add water with sugar and coffee preparing a 3. End breakfast 42 Flowchart Flowchart is another technique used in designing and representing algorithms. It is an alternative to pseudocode; whereas a pseudocode description is verbal while a flowchart is graphical in nature. 🞂 a graph consisting of geometrical shapes that are connected by flow lines 43 Flowchart Symbols Symbol Representation Symbo Representation l Start/Stop Decision Process Connector Input/Output Flow Direction Sub-module / Function (Barred Rectangle) 44 Flowchart Symbols – Start / Stop ▪ This symbol shows where a program starts and stops (program or module). ▪ To identify the beginning and Start end of a whole program. Stop ▪ The beginning terminal is labeled with start and the ending terminal is labeled with end or stop. 🗶 Start ▪ When the flowchart is for a module, the beginning terminal ✔ is labeled with the module name and the ending terminal is labeled with return or exit. 🗶 ✔ Stop 45 Flowchart Symbols – Process Used to show tasks such as calculations, assignment statements, incrementing, etc. Processes are labeled with the statement the task to be performed, for example: totalSales = subTotal + pstAmount + gstAmount Area = Length * Width Area = Length * Width firstName = "Sally" 46 Flowchart Symbols – Input/Output Used to show an operation that brings data into a program, or an operation that sends data out of the program. For example, getting values from the user or printing something on the screen. Input/output symbols are labeled with the statement that receives the input or generates the output, which could also include opening files and devices. Examples get stdNumber get stdNumber 47 Flowchart Symbols - Decision Used to identify a point in the program where a condition is evaluated. Conditions are used in if statements and looping. Decisions are labeled with the condition that they are testing, for example: numRecords > 10 foundMatch = true Yes No numRecords > 10 48 Sequence structure … statement_1 statement_2 statement_n Selection structure Yes then-part condition No else-part --------------------------------------------------------------------------------------------------------- ------------------------- Yes then-part condition 49 No Repetition structure Yes loop- body condition No 50 Used to connect two segments of flowchart that appear on the same page. This is done when your flowchart runs to the bottom of the page and we are out of room: end it with an on-page connector and then place another on-page connector in a free spot on the page, and continue the flowchart from that connector. On-page connectors are labeled with upper-case letters. The connector at the end of a segment of flowchart will match the connector that identifies the rest of the flowchart. For example, when we run out of room, end the flowchart with a connector labeled "A". 51 AA AA 52 Used to specify a function/module call or a group of related statements. Exampl e Start Submodule Submodule Return End 53 The benefits of flowcharts Flowcharts are better way of Communica tion communicating the logic of a system to all concerned. Effective With the help of flowchart, problem can be analysis analyzed in more effective way. Proper Program flowcharts serve as a good documenta program documentation, which is needed tion for various purposes. The flowcharts act as a guide or blueprint Efficient Coding during the systems analysis and program development phase. Proper Debugging The flowchart helps in debugging process. Efficient The maintenance of operating program Program becomes easy with the help of flowchart. It Maintenanc helps the programmer to put efforts more e efficiently on that part 54 Something to ponder What is the problem- solving process? 55 Problem Solving Process Input Process Output 56 Example 1 Calculate and display the price of apple(s). Lets assume the weight in kg and price per kg are given. Input Process Output Weight Price_per_kg Price = Weight * Price_per_kg Price 57 Flowchart: Calculate Price of Apples Start Input Quantity Input Price_per_kg Price = Quantity * Price_per_kg Output Price End 58 Programming Error Another challenge that awaits is program debugging. Debugging is defined as the process of finding and correcting errors in computer programs. No matter how careful you are as a programmer, most programs you write will contain errors. Either they won’t compile, or they won’t execute properly. This situation is something that happens very frequently to every programmer. You should take program debugging as a challenge, develop your debugging skills, and enjoy the process. There are three types of programming errors: Syntax errors Logic errors 59 Run-time errors Programming Error Syntax error: is violation of syntax rule, which define how the elements of a programming language must be written. They occur during the implementation phase and are detected by the compiler during the compilation process. Another name for syntax error is compilation error. Logic error: occur during the analysis, design, and implementation phases. We may choose an incorrect method of solution for the problem to be solved, mistakes in translating an algorithm into a program or design erroneous data for the program Run-time error: – are detected by the computer while the program is being executed. – they are caused by program instructions that require the computer to do something illegal, such 60 as attempting to store inappropriate data or divide a number by zero. Debug To fix the program error, programmer will do debugging task by using debugger Debugging process can be very frustrating especially involving huge amount of coding Good to have good programming style and documentation in coding! 61 Debug Debugger is a computer program that is used to test and debug other programs. Usually comes together with compilers Debugger will help programmer by provide list of error in compiling the program Still depends on 62 programmers to solve the Debugging technique Probe Put an external variable inside the program and try to force the program to output result in the middle. Good to trace modular Debug logic error or data error Trace Back-tracking or front- tracking Go step-by-step (or line- 63 by-line) to detect error. Testing and Verification In this phase, the main objective is to convince yourself and eventually your clients that the program will do what it is expected to do. In other words, you will want to verify that your program is correct. Program verification is the process of ensuring that a program meets user requirements. One of the techniques that can be used for program verification is program testing. Program testing is the process of executing a program to demonstrate its correctness. A program must be tested using a sufficiently large sample of carefully designed test data sets such that every logical path in the program is traversed at least once. You must continue to test your program until you are sure 64 that all statements in it are functioning correctly. Documentation Program documentation consists of these elements: A concise requirements specification Descriptions of problem inputs, expected outputs, constraints, and applicable formula A pseudocode and flowchart for its algorithm A source program listing A hardcopy of a sample test run of the program A user’s guide explaining to non- programmer users how the program should be used. Documentation can and should 65 End of Lecture 2 Let’s test your understanding on ALGORITHM 66 TEST 1 Write your pseudocode and then draw a flowchart for making a pot of coffee 67 TEST 2 Design the algorithm (pseudo-code) and flowchart for calculating the perimeter of a circle 68 TEST 3 Design the algorithm (use pseudo-code & flowchart) for summing the two numbers. 69 70 71

Use Quizgecko on...
Browser
Browser