introduction to computer programming problem solving & algorithms

Click here to load reader

Upload: malini

Post on 23-Feb-2016

81 views

Category:

Documents


0 download

DESCRIPTION

Introduction to Computer Programming Problem Solving & Algorithms. Muhammad Adnan Talib Lec#4 27 th Sep,2012 Computer Science Department COMSATS Institute of Information Technology Sahiwal. Problem Solving. Problem Solving is a key factor of human intelligence Consider the example. - PowerPoint PPT Presentation

TRANSCRIPT

Computer Programming

Muhammad Adnan TalibLec#427th Sep,2012Computer Science DepartmentCOMSATS Institute of Information TechnologySahiwal

Introduction to Computer ProgrammingProblem Solving & AlgorithmsProblem SolvingProblem Solving is a key factor of human intelligenceConsider the example

Problem SolvingFrom our daily life experience we know that the best way to solve a problem is to divide it into small steps, then to carry out these steps one by one to achieve the desired goal.

If look at a cheff following a recipe to make a meal we will observe that he is following certain steps.

Problem SolvingHow we give solution to a given problem?

Algorithms5Algorithm A concept that pervades all areas of computer science.

Algorithm is a process that a computer could carry out to complete a well defined task within finite time and resources.

The objective of computer science is to solve problems by developing, analyzing, and implementing algorithmic solutions. 56Al-Khwarizmi Principle All complex problems can be broken into simpler sub-problems. Solve a complex problem by breaking it down into smaller sub-problems and then solve them (in a specified order), one at a time. When all the steps are solved, the original problem itself has also been solved.This process is called Algorithm.67Computer ProgrammingComputer is a powerful toolIt is not intelligent!In order to use computer to solve our problems, we must tell it what we want done and the order in which we want it done. These instructions are called computer program. This process is called computer programming.The person giving these instructions is called a computer programmer.78Computer ProgrammingAnalyze the problemDevelop a sequence of instructions for solving the problem.Communicate it to the computer.

89Phases of the software life cycleRequirement definitionAnalysis and designCodingTestingImplementationMaintenance910Problem Solving TechniquesAsk questionsLook for things that are similarMeans-ends analysisDivide and ConquerMerging solutions1011Ask QuestionsAsk questions until you have developed a clear understanding of the problem.Who, What, Why, Where, When.What do I have to work with? (my data or input)How much data is there?What should my output look like?How many times is the process going to be repeated?What are the exceptions to the main course?What special error condition might come up?1112Look for things that are SimilarDo not reinvent the wheel!Draw Analogies1213Means-Ends analysisStarting point and ending state are known.You need to devise the transformation function.Ends are defined you need to analyze your means of getting between them.Lahore to IslamabadWhat are the options?Narrow down the options?Figure out the details?1314Divide and ConquerSame as the Al-khwarizmi Principle.Breakup the large problem into smaller units and then solve them one at a time.Building block approach.

1415Divide and ConquerHard ProblemHard Sub-problemEasy Sub-problemEasy Sub-problemEasy Sub-problemEasy Sub-problem1516Merging SolutionSometimes merging two independent solutions solves the problem more efficiently?Calculate AverageCount valuesSum ValuesDivide sum by count1617Problem Solving TechniquesWhat is the unknown?What is required?

What are the data?What is given?

What is the condition?By what condition the unknown is linked to the data?1718Conversion from Fahrenheit to CelsiusOutputTemperature in Celsius (C)

InputsTemperature in Fahrenheit (F)

Process

1819Calculate and print the average grade of 3 tests for the entire classInput3 test scores for each studentoutputAverage of 3 tests for each studentProcessGet three scoresAdd them togetherDivide by three to get the averagePrint the averageRepeat step 1 to 4 for next studentStop if there are no more students1920A flowchart is a visual or graphical representation of an algorithm.The flowchart employs a series of blocks and arrows, each of which represents a particular operation or step in the algorithm.The arrows represent the sequence in which the operations are implemented.Flow Charts2021Flowcharts Most Common SymbolsSymbolNameFunctionTerminalRepresents the beginning or end of a program.Flow-lineRepresents the flow of logic.

ProcessRepresents calculations or datamanipulation.

Input/OutputRepresents inputs or outputs of data and information.

DecisionRepresents a comparison, question, or decision that determines alternative paths to be followed.

2122Flowcharts An Example Find the solution of a quadratic equation Ax2+Bx+C=0, given A, B and C.STARTINPUT A, B, CCalculateR = SQRT(B2-4AC)AAX1 = (-B+R)/(2A)X2 = (-B-R)/(2A)PRINTA, B, C, X1, X2END2223Flow ChartingExpresses the flow of processing in a structured pictorial format.Processing StepsInput and Output StepsDecisionFlow of dataConnectorsTerminator2324Flow chart for Converting Fahrenheit into CelsiusGet temp. in FPrint C Calculate

StopBegin2425Add them togetherDivide the result by threeMore students?YesStopNoFlow chart for calculating average of three scoresGet three scoresPrint the average2526STARTINPUT A, BAdd A to B and store in COUTPUT CENDComparison of Algorithm representations in Natural language, flowchart and Pseudo-codeStep 1: Begin the calculations

Step 2: Input two values A and B

Step 3: Add the values

Step 4: Display the result

Step 5: End the calculationBEGIN Adder Input A and B C = A + B PRINT CEND AdderNatural languageFlowchartPseudo-code2627Algorithm Representation(Natural Languages)English or some other natural language.Are not particularly good:too verboseunstructuredtoo rich in interpretation (ambiguous)imprecise2728Algorithm Representation(Using Programming Language){ int I, m, Carry; int a[100], b[100], c[100]; cin >> m; for ( int j = 0 ; k > a[j]; cin >> b[j]; } Carry = 0; i = 0; while ( i < m ) { 2829Programming LanguagesAre not particularly good eitherToo many implementation details to worry aboutToo rigid syntaxEasy to lose sight of the real task2930Pseudo-codeWe need a compromise between the two: Pseudo-codeComputer scientists use pseudo-code to express algorithms:English like constructs (or other natural language), butmodeled to look like statements in typical programming languages. 3031Pseudo-code PrimitivesThree basic kind of operations:SequentialComputation ( Set )Input/Output ( Get ... / Print ... )ConditionalIf ElseIf Iterative / loopingRepeat ...While ...3132 Performs a computation and stores the result.ComputationExample:Set the value of C to (A + B) Set the value of location to 0Set the value of GPA to (sum / count) General format: Set the value of to 33VariablesA variable is a named storage. - A value can be stored into it, overwriting the previous value - Its value can be copied Examples: Set the value of A to 3 The variable A holds the value 3 after its executionSet the value of A to (A+1)Same as: add 1 to the value of A ( A is now 4)3334Not too Strict on SyntaxPseudo-code is kind of a programming language without a rigid syntax, for example we can write: Set the value of A to (B+C) as Set A to (B+C)or even:Set the value of sum to 0Set the value of GPA to 0as Set sum and GPA to 03435Sequential Operations - Input/OutputOutside worldInputOutputThe Computer needs to communicate with the outside world: INPUT operations allow the computing agent to receive from the outside world data values to use in subsequent computations.OUTPUT operations allow the computing agent to communicate results of computations to the outside world. 36InputGeneral format:

The computing agent (computer) suspends executions and waits for an input value. Get a value for

3637Input - ExamplesExamples:Get value for gradeGet values for N, MCan write:Get value for N1...Get value for N100asGet value for N1,..., N1003738OutputGeneral format:

The computing agent (computer) displays the value of the variable(s).

Print the value of Print the message, ""3839Output - ExamplesExamples:Print the value of gradePrint the message, "Hello"Can write:Print the value of N1...Print the value of N100asPrint the values of N1,..., N1003940ExampleWrite an algorithm to calculate the average of three numbers.Steps Operations 1 Get values for N1, N2, and N3 2 Set the value of Average to (N1+N2+N3)/3 3 Print the value of Average 4 Stop4041Conditional Operations If then operations for the then-part Else operations for the else-partEvaluate expression to see whether it is true or false. If true, then execute operations in then-partOtherwise, execute operations in else-part. 42Conditions, or Boolean ExpressionsA condition is one whose value is true or false, for example: 3 > 2is greater than (true) 3 = 2 is equal to (false) A > 2is true if As value is greater than 2 (at the time this is executed), false otherwise.43

E1 or E2true if at least one of them is true; false otherwise. E.g. 3 > 2 or 2 > 3 is true E1 and E2 true if both are true; false otherwise E.g. 3 > 2 and 2 > 3 is false not E true if E is false, false if E is trueConditions may be compounded.441. Get a value for A2. If A = 0 then 3. Print the message, The input is zero Else 4. Print the message, The input is not zeroExample1. Get a value for grade2. If grade < 1 or grade > 9 then 3. Print the message, Invalid grade Else 4. Set the value of total to (grade + total)45Iterative Operation - WhileWhile remains true do steps i to j step i:operation step i+1:operation step j:operationEvaluate If condition is true, execute steps i to j, then go back to i.3. Otherwise, if condition is false,continue execution from step j+1.45461 Get a value for count2 While count < 10 do3 Set square to (count * count)4 Print the values of count and square5 Add 1 to count6 StopExample47What happens when it gets executed?If count starts with 7, we get printout 7 49 8 64 9 81What if count starts with 11? Nothing is printed, loop is executed 0 times. While Loops48Set value of A equal to 1While A > 0 Print message, Enter an integer Get a value for AEnd of the loopStopWhat does the following algorithm do?Exercise49Tracing an algorithmThe current values of algorithm variables at various points during execution can be known by tracing the algorithm with a table called Trace Table 4950Trace TableProblem: Determine the value of the variable x and y after the following algorithm is executedPseudocode:x = 5Y = 7If x = 5 then y= 8else y= 0if y = 7 thenx = 6else x = 3if x = y then y = 0 Nesting???5051 Continued834.3834.2854.1853752-51yXStep No.Trace table for algorithm5152Find the phone number of a given Name in an (unsorted) list of names and their phone numbersNames Phone numbersN1 T1N2 T2N1000 T1000Sequential Search: an Example53Sequential Search: an Example

1234567891011553614442563521463541236452361442563551123441155521364528975541258Name to find:

Smith, John5354 1. Get value for Name 2. Get values for N1,,N1000 3. Get values for T1,,T1000 4. If Name = N1 then print the value of T1 5. If Name = N2 then print the value of T2 1002. If Name = N999 then print the value of T9991003. If Name = N1000 then print the value of 10001005. StopSequential Search: 1st Attempt55Get values for Name, N1,, N1000, T1,, T1000Set the value i to 1 and the value of Found to 0While Found = 0 AND i largest_so_far then Set the value of largest_so_far to Ai Set the value of location to I EndIF Add 1 to the value of iEnd of While loopPrint the values of largest_so_far and location Selection: Find The Largest Number

locationA1A2A3A4A5A6A7

Value5284864

locationA1A2A3A4A5A6A7

Value5284864

locationA1A2A3A4A5A6A7

Value5284864

locationA1A2A3A4A5A6A7

Value5284864

locationA1A2A3A4A5A6A7

Value5284864