Unit 171 Algorithms and Problem Solving Introduction Algorithm Design Algorithm Properties Algorithm Control Flow Examples Comparing Algorithms Exercises
Unit 172 Introduction A major phase of Software Design Life Cycle (SDLC) is the design phase. This phase involves the design of algorithms. It also involves the design of data structures.
Unit 173 Algorithm Design Algorithms are the details of the methods in the classes being designed. The methods are designed and specified after discovering the classes and relationships among them. A method usually uses other methods.
Unit 174 Algorithm Properties What is an Algorithm? An algorithm is an ordered sequence of instructions that is guaranteed to solve a specific problem Properties of Algorithm An algorithm should have the following properties: –No ambiguity in any instruction –No ambiguity which instruction is executed next –Finite number of instructions –Execution must halt and produce a result
Unit 175 Algorithm Control Flow How to represent an algorithm? Mostly pseudocode is used, which is a special set of English language constructs that look like statements of programming languages Syntax is flexible but simple and readable The constructs are of three types: –Sequential –Selection –Iteration
Unit 176 Comparing Algorithms Many ways to write an algorithm Desired attributes –Correctness –Ease of understanding –Elegance –Efficiency How to compare algorithms?
Unit 177 Example 1 Develop an algorithm to convert a temperature from Fahrenheit to Celsius Algorithm –get temperature –result = 5 / 9*(temperature – 32) –return result
Unit 178 Example 2 Develop an algorithm to withdraw a given amount from the balance Algorithm –get amount –if amount > balance print “cannot exceed balance” –else balance = balance - amount
Unit 179 Example 3 Develop an algorithm to determine if a given number n is prime Algorithm –get n –If n<2 isprime = false –else isprime = true –x = 2 –while isprime and x < sqrt(n) if x divides n isprime = false else x = x + 1 –return isprime
Unit 1710 Exercises 1.Develop an algorithm to check if a given integer is a perfect square or not. 2.Develop an algorithm to find the average and the standard deviation of an array of grades. 3.Develop an algorithm to display all prime numbers from 2 to 100.