GE8151 Problem Solving and Python Programming Notes Unit 1 -5
Notes
153 Pages
YB
Contributed by
Yash Baria
Loading
- UNIT IALGORITHMIC PROBLEM SOLVING1.1 ALGORITHMSIn computing, we focus on the type of problems categorically known as algorithmicproblems, where their solutions are expressible in the form of algorithms.The term ‗algorithm‘ was derived from the name of Mohammed al-Khowarizmi, aPersian mathematician in the ninth century. Al-Khowarizmi → Algorismus (in Latin) →Algorithm.An algorithm is a well-defined computational procedure consisting of a set ofinstructions that takes some value or set of values, as input, and produces some value orset of values, as output. In other word, an algorithm is a procedure that accepts data;manipulate them following the prescribed steps, so as to eventually fill the required unknownwith the desired value(s).People of different professions have their own form of procedure in their line of work,and they call it different names. For instance, a cook follows a procedure commonly knownas a recipe that converts the ingredients (input) into some culinary dish (output), after acertain number of steps.1.1.1 The Characteristics of a Good Algorithm Precision – the steps are precisely stated (defined). Uniqueness – results of each step are uniquely defined and only depend on the inputand the result of the preceding steps. Finiteness – the algorithm stops after a finite number of instructions are executed. Effectiveness – algorithm should be most effective among many different ways tosolve a problem. Input – the algorithm receives input. Output – the algorithm produces output. Generality – the algorithm applies to a set of inputs.1.2 BUILDING BLOCKS OF ALGORITHM (INSTRUCTIONS, STATE,CONTROL FLOW, FUNCTIONS)An algorithm is an effective method that can be expressed within a finite amount ofspace and time and in a well-defined formal language for calculating a function. Starting froman initial state and initial input, the instructions describe a computation that, when executed,AlgorithmInputOutputDownloaded from: annauniversityedu.blogspot.com
Page 1
- proceeds through a finite number of well-defined successive states, eventually producing"output" and terminating at a final ending state. The transition from one state to the next isnot necessarily deterministic; that algorithms, known as randomized algorithms.An instruction is a single operation, that describes a computation. When it executedit convert one state to other.Typically, when an algorithm is associated with processing information, data can beread from an input source, written to an output device and stored for further processing.Stored data are considered as part of the internal stateof the entity performing the algorithm.In practice, the state is stored in one or more data structures.The state of an algorithm is defined as its condition regarding stored data. The storeddata in an algorithm are stored as variables or constants. The state shows its current values orcontents.Because an algorithm is a precise list of precise steps, the order of computation isalways crucial to the functioning of the algorithm. Instructions are usually assumed to belisted explicitly, and are described as starting "from the top" and going "down to the bottom",an idea that is described more formally by flow of control.In computer science, control flow (or flow of control) is the order in whichindividual statements, instructions or function calls of an algorithm are executed or evaluated.For complex problems our goal is to divide the task into smaller and simpler functionsduring algorithm design. So a set of related sequence of steps, part of larger algorithm isknown as functions.1.2.1 Control FlowNormally Algorithm has three control flows they are: Sequence Selection IterationSequence: A sequence is a series of steps that occur one after the other, in the same orderevery time. Consider a car starting off from a set of lights. Imagine the road in front of the caris clear for many miles and the driver has no need to slow down or stop. The car will start infirst gear, then move to second, third, fourth and finally fifth. A good driver (who doesn‘thave to slow down or stop) will move through the gears in this sequence, without skippinggears.Selection: A selection is a decision that has to be made. Consider a car approaching a set oflights. If the lights turn from green to yellow, the driver will have to decide whether to stop orcontinue through the intersection. If the driver stops, she will have to wait until the lights aregreen again.Iteration: Iteration is sometimes called repetition, which means a set of steps which arerepeated over and over until some event occurs. Consider the driver at the red light, waitingDownloaded from: annauniversityedu.blogspot.com
Page 2
- for it to turn green. She will check the lights and wait, check and wait. This sequence will berepeated until the lights turn green.1.3 NOTATION OF ALGORITHMThere are four different Notation of representing algorithms: Step-Form Pseudocode Flowchart Programming Language1.3.1 Algorithm as Step-FormIt is a step – by – step procedure for solving a task or problem. The stepsmust be ordered, unambiguous and finite in number. It is English like representation of logicwhich is used to solve the problem.Some guidelines for writing Step-Form algorithm are as follows: Keep in mind that algorithm is a step-by-step process. Use begin or start to start the process. Include variables and their usage. If there are any loops, try to give sub number lists. Try to give go back to step number if loop or condition fails. Use jump statement to jump from one statement to another. Try to avoid unwanted raw data in algorithm. Define expressions. Use break and stop to terminate the process.For accomplishing a particular task, different algorithms can be written. Thedifferent algorithms differ in their requirements of time and space. The programmer selectsthe best suited algorithm for the given task to be solved.Let as look at two simple algorithms to find the greatest among three numbers,as follows:Algorithm 1.1:Step 1: Start.Step 2: Read the three numbers A,B,C.Step 3: Compare A and B. If A is greater perform step 4 else perform step 5.Step 4: Compare A and C. If A is greater, output ―A is greater‖ else output ―C is greater‖.Step 5: Compare B and C. If B is greater, output ―B is greatest‖ else output ―C is greatest‖.Step 6: Stop.Algorithm 1.2:Step 1: Start.Step 2: Read the three numbers A,B,C.Downloaded from: annauniversityedu.blogspot.com
Page 3
- Step 3: Compare A and B. If A is greater, store Ain MAX, else store B in MAX.Step 4: Compare MAX and C. If MAX is greater, output ―MAX is greater‖ else output ―C isgreater‖.Step 5: Stop.Both the algorithms accomplish same goal, but in different ways. Theprogrammer selects the algorithm based on the advantages and disadvantages of eachalgorithm. For example, the first algorithm has more number of comparisons, whereas insecond algorithm an additional variable MAX is required.In the Algorithm 1.1, Algorithm 1.2, step 1 and 2 are in sequence logic and step 3, 4,and 5 are in selection logic. In order to illustrate iteration logic, consider one more example.Design an algorithm for adding the test scores given as: 26, 49, 98, 87, 62, 75Algorithm 1.3:Step 1: StartStep 2: Sum = 0Step 3: Get a valueStep 4: sum = sum + valueStep 5: If next value is present, go to step 3. Otherwise, go to step 6Step 6: Output the sumStep 7: StopIn the Algorithm 1.3 step 5 have a go to statement with a back ward stepreference, so it means that iteration logic.1.3.2 PseudocodePseudocode ("sort of code") is another way of describing algorithms. It iscalled "pseudo" code because of its strong resemblance to "real" program code. Pseudocodeis essentially English with some defined rules of structure and some keywords that makeit appear a bit like program code.Some guidelines for writing pseudocode are as follows.Note: These are not "strict" guidelines. Any words used that have similar form and functionmay be used in an emergency - however, it would be best to stick to the pseudocode wordsused here. for start and finish BEGIN MAINPROGRAM, END MAINPROGRAM -this is often abbreviated to BEGIN and END - especially in smaller programs for initialization INITIALISATION, END INITIALISATION - this part isoptional, though it makes your program structure clearer for subprogram BEGIN SUBPROGRAM, END SUBPROGRAM for selection IF, THEN, ELSE, ENDIF for multi-way selection CASEWHERE, OTHERWISE, ENDCASE for pre-test repetition WHILE, ENDWHILEDownloaded from: annauniversityedu.blogspot.com
Page 4
- for post-test repetition REPEAT, UNTIL Keywords are written in capitals. Structural elements come in pairs, eg for every BEGIN there is an END, forevery IF there is an ENDIF, etc. Indenting is used to show structure in the algorithm. The names of subprograms are underlined. This means that when refiningthe solution to a problem, a word in an algorithm can be underlined and asubprogram developed. This feature is to assist the use of the ‗top-down‘development concept.1.3.3 FlowchartsFlowcharts are a diagrammatic method of representing algorithms. They usean intuitive scheme of showing operations in boxes connected by lines and arrows thatgraphically show the flow of control in an algorithm.Table 1.1lists the flowchart symbol drawing, the name of the flowchartsymbol in Microsoft Office (with aliases in parentheses), and a short description of where andhow the flowchart symbol is used.Table 1.1: Flowchart SymbolsSYMBOLNAME(ALIAS)DESCRIPTIONFlow Line(Arrow,Connector)Flow line connectors show the direction that the processflows.Terminator(TerminalPoint, Oval)Terminators show the start and stop points in a process.Data(I/O)The Data flowchart shape indicates inputs to and outputsfrom a process. As such, the shape is more often referredto as an I/O shape than a Data shape.DocumentPretty self-explanatory - the Document flowchart symbolis for a process step that produces a document.ProcessShow a Process or action step. This is the most commonsymbol in flowcharts.DecisionIndicates a question or branch in the process flow.Typically, a Decision flowchart shape is used when thereare 2 options (Yes/No, No/No-Go, etc.)Connector(Inspection)This symbol is typically small and is used as a Connectorto show a jump from one point in the process flow toanother. Connectors are usually labeled with capital letters(A, B, AA) to show matching jump points. They are handyfor avoiding flow lines that cross other shapes and flowlines. They are also handy for jumping to and from a sub-processes defined in a separate area than the mainflowchart.Downloaded from: annauniversityedu.blogspot.com
Page 5
- PredefinedProcess(Subroutine)A Predefined Process symbol is a marker for anotherprocess step or series of process flow steps that areformally defined elsewhere. This shape commonly depictssub-processes (or subroutines in programming flowcharts).PreparationAs the names states, any process step that is a Preparationprocess flow step, such as a set-up operation.MagneticDisk(Database)The most universally recognizable symbol for a datastorage location, this flowchart shape depicts a database.1.3.4 Control Structures of Pseudocode and FlowchartsEach control structures can be built from the basic elements as shown below.Sequence: A sequence is a series of steps that take place one after another. Each step isrepresented here by a new line.Our sequence example of changing gears could be described as follows :PseudocodeFlowchartBEGIN1st Gear2nd Gear3rd Gear4th Gear5th GearENDPseudocodeFlowchartBEGINStatementStatementENDDownloaded from: annauniversityedu.blogspot.com
Page 6
- Selection : A Selection is a decision. Some decisions may be answered as Yes or No. Theseare called binary selections. Other decisions have more than two answers. These arecalled multiway selections.A binary selection may be described in pseudocode and flow chart as follows :PseudocodeFlowchartIF (question) THENstatementELSEstatementENDIFAn example of someone at a set of traffic lights follows :PseudocodeFlowchartIF (lights are green) THENGoELSEStopENDIFA Multiway Selection may be described as follows :PseudocodeFlowchartCASEWHERE (question)Alternative 1: StatementAlternative 2 : StatementOTHERWISE : StatementENDCASEDownloaded from: annauniversityedu.blogspot.com
Page 7
- An example of someone at a set of traffic lights follows :PseudocodeFlowchartCASEWHERE Lights are :Green : GoAmber : SlowdownRed : StopENDCASERepetition: A sequence of steps which are repeated a number of times, is called repetition.For a repeating process to end, a decision must be made. The decision is usually called a test.The position of this test divides repetition structures into two types : Pre-test and Post-testrepetitions.Pre-test repetitions (sometimes called guarded loops) will perform the test before any partof the loop occurs.Post-test repetitions (sometimes called un-guarded loops) will perform the test after themain part of the loop (the body) has been performed at least once.Pre-test repetitions may be described in as follows :PseudocodeFlowchartWHILE (question)StatementENDWHILEDownloaded from: annauniversityedu.blogspot.com
Page 8
- A traffic lights example follows :PseudocodeFlowchartWHILE (lights are not green)waitENDWHILEPost-test repetitions may be described as follows:A traffic lights example follows :PseudocodeFlowchartREPEATWaitUNTIL lights are greenPseudocodeFlowchartREPEATStatementUNTIL (Question)Downloaded from: annauniversityedu.blogspot.com
Page 9
- Sub-Programs: A sub-program is a self-contained part of a larger program. The use of sub-programs helps with "Top-Down" design of an algorithm, by providing a structure throughwhich a large and unwieldy solution may be broken down into smaller, more manageable,components.A sub-program is described as:PseudocodeFlowchartsubprogramConsider the total concept of driving a car. This activity is made up of a number of sub-processes which each contribute to the driver arriving at a destination. Therefore, driving mayinvolve the processes of "Starting the car"; "Engaging the gears"; "Speeding up and slowingdown"; "Steering"; and "Stopping the car".A (not very detailed) description of driving may look something like:PseudocodeFlowchartBEGINStart CarEngage GearsNavigate CarStop CarENDDownloaded from: annauniversityedu.blogspot.com
Page 10
Download this file to view remaining 143 pages
Related documents:
- HIST 9 UNIT 2-3 - MCQ
- Public Administration (Paper I) 2020 Question Paper
- Dynamics of Machines Solved MCQs Mechanical - MCQ
- Social Construction Of Gender Unit-4 Quetions with answers - Question Bank
- MG6851 Principles of Management qbank - Question Bank
- MA8353 TRANSFORMS AND PARTIAL DIFFERENTIAL EQUATIONS notes - Notes
- Rotationl Motion Notes and MCQs - Notes
- Public Relationship (PR) - Principles of Event Management - Notes
- Logic (Mathematical Reasoning) (Solved MCQs and Notes) - Notes
- Sociology (Paper II) 2019 Question Paper - Question Paper
- CONDUCT OF AN EVENT - Principles of Event Management - Notes
- Social Construction Of Gender Unit-3 Quetions with answers - Question Bank
- Root of equation & Error approximation - Assertion and Reasoning
- UPSC 2021 Prelims [SCIENCE AND TECHNOLOGY Answer Key with Explanation] - Question Bank
- Modern India –II Unit 4 Questions with answers - Question Bank
- Applied Mathematics
- Public Administration (Paper I) 2015 Question Paper - Question Paper
- Business Ethics MCQs with Answers - MCQ
- Atoms and Nucleus Notes and MCQs - Notes
- EXIM TRADE - INTERNATIONAL BUSINESS - Notes