Download presentation
Presentation is loading. Please wait.
1
1 Algorithms and Problem Solving
2
2 Outline Problem Solving Problem Solving Strategy Algorithms Sequential Statements Examples
3
3 Problem Solving Solving a problem means that we know the way or the method to follow manually from the start till the end. Having the method known, the same method is used by the computer to solve the problem but faster with higher precision. If we do not know how to solve a problem ourselves, the computer will not be of any help in this regard. The strategy for solving a problem goes through the following stages: Analysis: in this stage, we should find what the problem should do. Design : the way or method of how your problem is solved is produced Implementation: the method found in design is then coded here in a given programming language. Testing: here we verify that the program written is working correctly Deployment : finally the program is ready to use
4
4 Problem Solving Strategy
5
5 Algorithms An algorithm is a sequence of instructions that solve a problem with the following properties: No ambiguity in any instruction No ambiguity which instruction is next Finite number of instructions Execution must halt The description of the instructions can be given in English like statements called pseudo-code The flow control of instructions has three types: Sequential Selection Iteration
6
6 Sequential Statements Instructions in this type are executed one after the other in sequence These statements include: Assignment statement Method calls
7
7 Example1 Write a program that assigns the Cartesian coordinates of two points (x1, y1) and (x2, y2) and displays the distance between them using the following formula. Algorithm: »x1 = 1 »y1 = 1 »x2 = 4 »y2 = 6 »distance = sqrt( (x2 – x1) ^ 2 + (y2 – y1) ^ 2 ) »print distance
8
8 Example1 (cont'd) Java code: public class Distance { public static void main(String[] args) { double x1, y1, x2, y2, dist; x1 = 1.0; y1 = 1.0; x2 = 4.0; y2 = 6.0; dist = Math.sqrt(Math.pow(x2-x1,2)+ Math.pow(y2-y1,2)); System.out.println("The distance is " + dist); }
9
9 Example2 Write a program that finds the area of a triangle given the length of its sides: a, b, c. Use a = 3, b = 4, c = 5 to test your solution. Algorithm: »a = 3 »b = 4 »c = 5 »s = (a + b + c) / 2 »area = sqrt( s* (s – a) * (s – b) * (s – c) ) »print area
10
10 Example2 (cont'd) Java code: public class Distance { public static void main(String[] args) { double a, b, c, area; a = 3.0; b = 4.0; c = 5.0; s = (a + b + c ) / 2.0; area = Math.sqrt(s * (s - a) * (s – b) * (s – c) ); System.out.println("The area is " + area); }
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.