1 / 61

Introduction to Computer Programming Problem Solving & Algorithms

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.

malini
Download Presentation

Introduction to Computer Programming Problem Solving & Algorithms

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to Computer ProgrammingProblem Solving & Algorithms Muhammad AdnanTalib Lec#4 27th Sep,2012 Computer Science Department COMSATS Institute of Information Technology Sahiwal

  2. Problem Solving • Problem Solving is a key factor of human intelligence • Consider the example

  3. Problem Solving • From 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.

  4. Problem Solving • How we give solution to a given problem? Algorithms

  5. Algorithm 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.

  6. Al-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.

  7. Computer Programming • Computer is a powerful tool • It 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.

  8. Computer Programming • Analyze the problem • Develop a sequence of instructions for solving the problem. • Communicate it to the computer.

  9. Phases of the software life cycle • Requirement definition • Analysis and design • Coding • Testing • Implementation • Maintenance

  10. Problem Solving Techniques • Ask questions • Look for things that are similar • Means-ends analysis • Divide and Conquer • Merging solutions

  11. Ask Questions • Ask 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?

  12. Look for things that are Similar • Do not reinvent the wheel! • Draw Analogies

  13. Means-Ends analysis • Starting 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 Islamabad • What are the options? • Narrow down the options? • Figure out the details?

  14. Divide and Conquer • Same as the Al-khwarizmi Principle. • Breakup the large problem into smaller units and then solve them one at a time. • Building block approach.

  15. Easy Sub-problem Hard Sub-problem Easy Sub-problem Easy Sub-problem Easy Sub-problem Divide and Conquer Hard Problem

  16. Merging Solution • Sometimes merging two independent solutions solves the problem more efficiently? • Calculate Average • Count values • Sum Values • Divide sum by count

  17. Problem Solving Techniques • What 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?

  18. Conversion from Fahrenheit to Celsius • Output • Temperature in Celsius (C) • Inputs • Temperature in Fahrenheit (F) • Process

  19. Calculate and print the average grade of 3 tests for the entire class • Input • 3 test scores for each student • output • Average of 3 tests for each student • Process • Get three scores • Add them together • Divide by three to get the average • Print the average • Repeat step 1 to 4 for next student • Stop if there are no more students

  20. Flow Charts • A 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.

  21. Flowcharts – Most Common Symbols Function Symbol Name Terminal Represents the beginning or end of a program. Flow-line Represents the flow of logic. Process Represents calculations or data manipulation. Input/Output Represents inputs or outputs of data and information. Decision Represents a comparison, question, or decision that determines alternative paths to be followed.

  22. A START X1 = (-B+R)/(2A) X2 = (-B-R)/(2A) INPUT A, B, C Calculate R = SQRT(B2-4AC) PRINT A, B, C, X1, X2 A END Flowcharts – An Example Find the solution of a quadratic equation Ax2+Bx+C=0, given A, B and C.

  23. Flow of data Connectors Flow Charting Expresses the flow of processing in a structured pictorial format. Input and Output Steps Processing Steps Decision Terminator

  24. Begin Calculate Print ‘C’ Stop Flow chart for Converting Fahrenheit into Celsius Get temp. in ‘F’

  25. Get three scores Add them together Print the average Divide the result by three More students? Yes No Stop Flow chart for calculating average of three scores

  26. START INPUT A, B Add A to B and store in C OUTPUT C END Comparison of Algorithm representations in Natural language, flowchart and Pseudo-code Step 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 calculation BEGIN Adder Input A and B C = A + B PRINT C END Adder Natural language Flowchart Pseudo-code

  27. Algorithm Representation(Natural Languages) • English or some other natural language. • Are not particularly good: • too verbose • unstructured • too rich in interpretation (ambiguous) • imprecise

  28. Algorithm Representation(Using Programming Language) { int I, m, Carry; int a[100], b[100], c[100]; cin >> m; for ( int j = 0 ; k <= m-1 ; j++ ) { cin >> a[j]; cin >> b[j]; } Carry = 0; i = 0; while ( i < m ) { …

  29. Programming Languages • Are not particularly good either • Too many implementation details to worry about • Too rigid syntax • Easy to lose sight of the real task

  30. Pseudo-code • We need a compromise between the two: Pseudo-code • Computer scientists use pseudo-code to express algorithms: • English like constructs (or other natural language), but • modeled to look like statements in typical programming languages.

  31. Pseudo-code Primitives Three basic kind of operations: • Sequential • Computation ( Set … ) • Input/Output ( Get ... / Print ... ) • Conditional • If … Else • If … • Iterative / looping • Repeat ... • While ...

  32. Computation General format: Performs a computation and stores the result. Set the value of <variable> to <expression> Example: Set the value of C to (A + B) Set the value of location to 0 Set the value of GPA to (sum / count)

  33. Variables A 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 execution Set the value of A to (A+1) Same as: add 1 to the value of A ( A is now 4)

  34. Not too Strict on Syntax • Pseudo-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 0 • Set the value of GPA to 0 • as • Set sum and GPA to 0

  35. Input Output Sequential Operations - Input/Output Outside world • The Computer needs to communicate with the outside world: • INPUToperations 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.

  36. Input General format: The computing agent (computer) suspends executions and waits for an input value. Get a value for <variable>

  37. Input - Examples • Examples: • Get value for grade • Get values for N, M • Can write: • Get value for N1 • ... • Get value for N100 • as • Get value for N1,..., N100

  38. Output General format: The computing agent (computer) displays the value of the variable(s). Print the value of <variable> Print the message, "<text>"

  39. Output - Examples • Examples: • Print the value of grade • Print the message, "Hello" • Can write: • Print the value of N1 • ... • Print the value of N100 • as • Print the values of N1,..., N100

  40. Example • Write 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 Stop

  41. Conditional Operations If <condition> then operations for the then-part Else operations for the else-part • Evaluate <condition> expression to see whether it is true or false. • If true, then execute operations in then-part • Otherwise, execute operations in else-part.

  42. Conditions, or Boolean Expressions • A condition is one whose value is true or false, for example: • 3 > 2 is greater than (true) • 3 = 2 is equal to (false) • A > 2 is true if A’s value is greater than 2 (at the time this is executed), false otherwise.

  43. Conditions may be compounded E1 or E2 true 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 true

  44. Example 1. Get a value for A 2. If A = 0 then 3. Print the message, “The input is zero” Else 4. Print the message, “The input is not zero” 1. Get a value for grade 2. If grade < 1 or grade > 9 then 3. Print the message, “Invalid grade” Else 4. Set the value of total to (grade + total)

  45. Iterative Operation - While While <condition> remains true do steps i to j step i: operation step i+1: operation … step j: operation • Evaluate <condition> • 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.

  46. Example 1 Get a value for count 2 While count < 10 do 3 Set square to (count * count) 4 Print the values of count and square 5 Add 1 to count 6 Stop

  47. While Loops What happens when it gets executed? If count starts with 7, we get printout 7 49 8 64 9 81 What if count starts with 11? Nothing is printed, loop is executed 0 times.

  48. Exercise What does the following algorithm do? Set value of A equal to 1 While A > 0 Print message, “Enter an integer” Get a value for A End of the loop Stop

  49. Tracing an algorithm The current values of algorithm variables at various points during execution can be known by tracing the algorithm with a table called Trace Table

  50. Trace Table Problem: Determine the value of the variable x and y after the following algorithm is executed Pseudocode: x = 5 Y = 7 If x = 5 then y= 8 else y= 0 if y = 7 then x = 6 else x = 3 if x = y then y = 0 Nesting???

More Related