Lecture 05: Algorithms

Download Report

Transcript Lecture 05: Algorithms

Algorithms and Problem Solving
1
Outline





Problem Solving
Problem Solving Strategy
Algorithms
Sequential Statements
Examples
2
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
3
Problem Solving Strategy
4
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
5
Sequential Statements

Instructions in this type are executed one after the other in sequence

These statements include:
 Assignment statement
 Method calls
6
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.
d  ( x1  x2 ) 2  ( y1  y2 ) 2

Algorithm:
» x1 = 1
» y1 = 1
» x2 = 4
» y2 = 6
» distance = sqrt( (x2 – x1) ^ 2 + (y2 – y1) ^ 2 )
» print distance
7
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);
}
}
8
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.
area  s  s  a   s  b   s  c 
s

abc
2
Algorithm:
» a=3
» b=4
» c=5
» s = (a + b + c) / 2
» area = sqrt( s* (s – a) * (s – b) * (s – c) )
» print area
9
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);
}
}
10