100 likes | 185 Views
TA C252 Computer Programming. Agenda. Top-Down Design Examples. Top-down Design. Design Approach Principle Divide and Combine Steps Decompose the problem into sub-problems Solve the sub-problems Combine the (sub-)solutions. Top-down Design. How do you solve the sub-problem?
E N D
TA C252 Computer Programming Agenda Top-Down Design Examples Sundar B. TA C252
Top-down Design • Design Approach • Principle • Divide and Combine • Steps • Decompose the problem into sub-problems • Solve the sub-problems • Combine the (sub-)solutions
Top-down Design • How do you solve the sub-problem? • Divide-and-combine again! • Steps • Divide the problem into sub-problems • Repeat step 1 for each sub-problem until the problem is small enough to have an atomic solution. 3. Combine the solutions.
Top-Down Design – Example 1 • Problem: Compute a solution to a quadratic equation. • Input: Real Numbers a,b,c • Output: x such that ax^2 + bx + c = 0 • Fact: • x = (-b + sqrt(b^2 – 4ac)) / (2a) is a solution.
Top-Down Design – Example 1 Compute x s.t. ax^2+bx+c=0 Compute (-b + sqrt(b^2 – 4ac)) / (2a) Compute (-b + d) / (2a) Compute d = sqrt(b^2 – 4ac)
Top-Down Design – Example 2 • Compute xy where y is a power of 2. • Input: x and y • Output: xy
Top-Down Design – Example 2 Compute xy (y = 2k for some k>=0) Square the result Compute xy/2
Top-Down Design – Example 2 Compute xy (y = 2k for some k>=0) Square the result Compute xy/2 … x is the result Compute x1
Top-Down Design – Example 2 Compute xy (y = 2k for some k>=0) Square the result Compute xy/2 How many divisions? … x is the result Compute x1
Top-Down Design – Example 2 int power2(int x, int y) { int y1 = 1; int res = x; while (y1 < y) { x = x * x; y = 2 * y; } }