Title: Algorithms
1Algorithms
2Topics to Cover
- Recall Algorithm Definition
- An Algorithm Average
- Fundamental Algorithmic Constructs
- Another Algorithm Euclids
- Recall Algorithm Characteristics
- From Pseudo-Code to Java
- Algorithmic Constructs Java Syntax
- A Java Program Average
- Another Java Program Euclid
- The Program Development Algorithm
- Stepwise Refinement
- Algorithm vs. Program
3Recall Algorithm Definition
- An ordered set of effective, unambiguous,
commands for a task which, when executed,
terminates. - Where does the term algorithm come from then?
- From mathematics, actually
4Recall Algorithm Definition
- Historians generally believe the word algorithm
came from an Arabic author of textbooks in the
9th century - Abu Abdullah Muhammad bin Musa al-Khwarizmi
- Examples from mathematics
- Long division algorithm
- Euclidean algorithm for finding the greatest
common divisor of 2 positive integers
5An Algorithm Average
Average Algorithm This algorithm computes the
average of three numbers. ASSIGN howmany
3ASSIGN sum 0 FOR howmany repetitions DO
GET number ADD number to sumEND of
repetitions REPORT average is sum DIVIDED BY
howmany
6An Algorithm Average
- Observe
- Once an algorithm is specified, one no longer
requires an understanding of the principles of
the algorithm to solve the problem - Rather, one only needs to blindly follow the
steps of the algorithm (which is exactly what a
computer does with a computer program!) - Recall an algorithm is written in a pseudo-code
form. (Like code, but not quite translation to
code for a particular programming language would
be fairly simple though.)
7An Algorithm Average
- The Average Algorithm, although simple, provides
examples of some of the following algorithmic
constructs provided by high-level programming
languages - Data storage/retrieval
- Data manipulation
- Sequential execution
- Conditional execution
- Repetition
- We will look at each of these fundamental
algorithm (and, therefore, programming)
constructs, in turn
8Fundamental Algorithm Constructs
- Data storage/retrieval (aka input/output)
- Information (data) is stored in variables so that
it can be retrieved and used later. - Pseudo-code keywords
- GET ltvariable namegt
- obtain a value (e.g. from the user) and store it
in main memory - REPORT ltvariable namegt
- display a value stored in main memory to the user
- ASSIGN ltvariable namegt ltvaluegt
- store a value in a location in main memory
- LET ltvariable namegt BE ltvaluegt
- store a value in a location in main memory
- Examples from the Average Algorithm?
9Fundamental Algorithm Constructs
- Data manipulation
- Information is used to create new or additional
information - Pseudo-code keyword
- none data to be manipulated is obtained simply
by giving the location of its storage (i.e. its
variable name) - Example from the Average Algorithm?
10Fundamental Algorithm Constructs
- The previous algorithmic constructs deal with
data. The remaining constructs deal with flow of
control - Which instruction is executed next?
- Sequential execution
- Instructions are executed one after another in
the order given - Pseudo-code keyword
- none - default mode of execution
- Example from the Average Algorithm?
11Fundamental Algorithm Constructs
- Conditional execution (aka selection)
- Instruction(s) may or may not be executed,
depending on some condition(s) at time of
execution (aka run time). - Pseudo-code keywords
- IF-THEN
- IF-THEN-ELSE
- Example from the Average Algorithm?
12Fundamental Algorithm Constructs
- Observe Three types of conditionals
- IF-THEN
- Decides whether or not some sequence of
instructions will be executed - IF-THEN-ELSE
- Selects one of two sequences of instructions to
be executed - How is one of many sequences of instructions
selected to be executed? ( nested IF-THEN-ELSE) - Examples?
13Fundamental Algorithm Constructs
- Repetition
- A sequence of instructions is executed 0, 1, or
more times - Also called a loop
- Pseudo-code keywords
- WHILE
- FOR
- DO-WHILE
- Example from the Average Algorithm?
14Fundamental Algorithm Constructs
- Important loop design considerations
- How many repetitions?
- Termination condition?
- If the loop never terminates, we have what is
called an infinite loop. - What happens if an infinite loop is present in
an algorithm? in a program? - Initial conditions?
15Fundamental Algorithm Constructs
- There are 2 types of loops
- Pre-tested
- Body executed 0 or more times
- Two main forms
- FOR ltnumber of repetitionsgt DO ltloop
body statementsgt - Useful when the number of times the loop body
must be executed is known when the looping starts - Executes the ltloop body statementsgt ltnumber of
repetitionsgt times - Example?
16Fundamental Algorithm Constructs
- The other form
- WHILE ltconditiongt DO ltloop body statementsgt
- Useful when the number of repetitions is unknown
when the looping starts - Continues to repeat the execution of the ltloop
body statementsgt as long as ltconditiongt is true - Example?
17Fundamental Algorithm Constructs
- Post-tested
- Loop body executed 1 or more times
- Continues to repeat the execution of the ltloop
body statementsgt as long as ltconditiongt is
trueDO ltloop body statementsgt WHILE
ltconditiongt - Example?
18Fundamental Algorithm Constructs
- Notes
- The WHILE and DO-WHILE loops are indefinite
loops. - The FOR loop, on the other hand, is a definite
loop. - Why?
19Algorithms with Flow Charts
- It can be useful to model flow of control with
flow charts. - Flow charts can help to visualize algorithms and
how they would beexecuted. - Other diagramming techniques are more expressive
and more commonly used these days. - But, flow charting tends to be the simplest.
- You will see some of the other approaches later,
in other courses.
20Algorithms with Flow Charts
21Algorithms with Flow Charts
Flow chart of the Average Algorithm
22Another Algorithm Euclids
Euclids Algorithm This algorithm computes the
greatest common divisor. GET two integers
biggest, smallest DO DIVIDE biggest by
smallest LET remainder be the remainder of
the division IF remainder is not zero
THEN LET biggest take the value of the
smallest LET smallest take
the value of the remainderWHILE remainder is not
zero REPORT greatest common divisor is smallest
23Another Algorithm Euclids
Flow chart of Euclids Algorithm
24Another Algorithm Euclids
- First step understand the problem GCD
- Next, identify
- Keywords
- Variables
- Assignments (i.e. when a value is stored in
memory) - I/O (input/output)
- Selection
- Repetition
- Observe
- Indentation, spacing, fonts (Are they
important? Why? Why not?)
25Another Algorithm Euclids
- Discussion points
- Is the loop pre-tested or post-tested?
- Can a post-tested loop be written as a pre-tested
loop? - Can a pre-tested loop be written as a post-tested
loop? - What kind of selection is involved?
- When the last statement is executed is one of the
original numbers reported? - Desk-check (aka trace) the algorithm.
26Recall Algorithm Characteristics
- Those characteristics were
- Ordered set of instructions
- Effective instructions
- Unambiguous instructions
- Terminates
- Does Euclids Algorithm fulfill these
requirements? does the Average Algorithm? - Give of a sequence of steps that is not an
algorithm.
27Recall Algorithm Characteristics
- There are other concerns for algorithms besides
those characteristics. - Efficiency This can be a very important concern
for algorithms. Two key types - Time efficiency
- Space efficiency
- Correctness Of course, this tends to be the
most important concern! - If the algorithm is not correct, and does notdo
the task it was intended for, what goodis it?
28From Pseudo-Code to Java
- Once satisfied with an algorithm, the programmer
translates the algorithm into a program. - The algorithm was written in pseudo-code.
- The program is to be written in a programming
language of some kind. - In our case, we are particularly interested in
translating algorithms into Java.
29From Pseudo-Code to Java
- To do this, one needs to know how each
algorithmic construct - data storage/retrieval
- data manipulation
- sequential execution
- conditional execution
- repetition
- is represented in Java that is Java syntax.
- We will now briefly see how some algorithmic
constructs are represented in Java. - We will be seeing these in more detail later
this is just a first look
30Algorithmic Constructs Java Syntax
- Important to distinguish
- Semantics vs. syntax
- Meaning vs. representation
- Concept vs. symbol
31Algorithmic Constructs Java Syntax
- Data storage/retrieval
- REPORT
- System.out.println displays items separated by
(called the concatenation operator) to the
screen.
System.out.println("The average of the numbers is
" (float) sum /
howmany)
32Algorithmic Constructs Java Syntax
- GET consists of two Java statements a prompt
statement and an input statement - System.out.print - displays a message to the
screen - parseInt - a method that obtains an integer from
a line of keyboard input - Integer - the class where the parseInt method
is found - keyboard.readLine() reads in a line of input
typed by the user
System.out.print("Please enter number " i "
")aNumber Integer.parseInt(keyboard.readLine()
)
33Algorithmic Constructs Java Syntax
- LET is represented in Java by the assignment
statement - is the assignment operator
- Note it does not represent equals in the
mathematical sense! - int indicates the type of variable
int howmany3
34Algorithmic Constructs Java Syntax
- Data manipulations
- A mathematical operation shown here division
- (float) is called a type cast, which deals with
a conversion of the representation of data
(float implies a real number as opposed to an
integer) - Sequential execution default
- Statements are executed in the order given, one
after the other
(float) sum / howmany
35Algorithmic Constructs Java Syntax
- Conditional execution
- keyword if represents a decision to be made
based on the condition following it in
parentheses - remainder is a variable (storage place in memory)
- ! represents not equal
- represents a block of code
- If the condition is true, the statements in the
associated block are executed if the condition
is not true, the statements in the associated
block are not executed
if (remainder ! 0) biggest smallest
smallest remainder
36Algorithmic Constructs Java Syntax
- Repetition
- An example of a loop, indicated by the keyword
for - (int i1 i lt howmany i) indicates
- a start condition (initialization)
- termination condition (when to quit repeating)
- a statement to be executed every time
- The loop body
- is located inside the curly brackets
- contains the statements to be repeatedly executed
- Observe this is a pre-tested loop
for (int i1 i lt howmany i)
System.out.print("Please enter number " i "
") aNumber Integer.parseInt(keyboard.r
eadLine()) sum sum aNumber
37A Java Program Average
- The following slide presents a Java program
developed from the Average Algorithm.
38/ Average.java CS026 Lecture Notes Example
Task calculates the average of three
numbers using fundamental programming
concepts /import java.io.public class
Average public static void main(String
args) throws Exception BufferedReader
keyboard new BufferedReader(
new InputStreamReader(System.in),1)
int howmany3 int sum0 int
aNumber for (int i1 i lt howmany i)
System.out.print("Please enter number
" i " ") aNumber
Integer.parseInt(keyboard.readLine())
sum sum aNumber
System.out.println() System.out.println("Th
e average of the numbers is "
(float) sum / howmany)
39A Java Program Average
Screenshot of BlueJ output from running the
Average program.
40Another Java Program Euclid
- The following slides contain a Java program
developed from Euclids Algorithm.
41/ file name Euclid.java CS026 Lecture
Notes Example Task calculates the greatest
common divisor of two integers, using
fundamental programming concepts and
Euclid's algorithm / import
java.io. public class Euclid
42 public static void main(String args) throws
Exception BufferedReader keyboard new
BufferedReader
(new InputStreamReader(System.in),1) int
biggest / first user input largest of 2
integers / int smallest / second user
input smallest of 2 integers /
System.out.print("Please enter an integer ")
biggest Integer.parseInt(keyboard.readLine())
System.out.print("Please enter an
integer smaller than "
biggest " ") smallest
Integer.parseInt(keyboard.readLine())
System.out.print("The greatest common divisor of
" biggest " and "
smallest " is ") int remainder
/ remainder from integer division / do
remainder biggest smallest
if (remainder ! 0) biggest
smallest smallest remainder
while (remainder ! 0)
System.out.println(smallest)
43Another Java Program Euclid
Screenshot of BlueJ output from running the
Euclid program.
44Sample Java ProgramsObservations
- Things to observe regarding the programs
- Program names Average, Euclid
- File names Average.java, Euclid.java
- Java statement terminator
- Form spacing, indentation, upper/lower case
- Comments audience, importance
- Compound statements
- How to run (i.e. execute)? (enter with editor,
compile, run) - See Program Development Algorithm, coming shortly
- More on this in the labs and your first
assignment
45Sample Java ProgramsA Word on Keywords
- Recall a keyword is a word that has special
meaning in Java. - Here is a very brief introduction to some of the
keywords in the programs (we will see all of
these in much more detail later ) - class the unit of organization for Java
programs - public an accessibility modifier indicates
whether or not the code is available for use by
other code (other possibilities are private,
protected) - static indicates a certain type of subsection
of code - void indicates that no value is present here
(other possibilities are int, double) - throws Exception deals with error handling
- import tells what predefined Java code is
required
46The Program Development Algorithm
- The following is an algorithm used by programmers
in developing Java programs. - It isnt a perfect algorithm for doing so,but it
isnt bad either.
47 Java Programming for Programmers DEFINE the
problemDEVELOP an algorithmTRANSLATE the
algorithm into JavaENTER the Java program into a
file, using an editor DO DO
CREATE Java bytecode representation of the
program (i.e.
compile javac) RUN the program with
test input (java) CHECK the output
IF the output is not correct
determine problem
determine correction edit
program with the correction WHILE the
output is not correctWHILE there are more test
cases
48More On Java Programming
- More details about Java programming
- Regarding file names
- Each Java program has a name
- A program must be stored in a file named with the
program name and the extension .java - e.g. program name HelloWorldfile
HelloWorld.java contains the Java code - Regarding compiling the source code
- The compiler creates the bytecode version of the
code and stores it in a file with the extension
.class - e.g. javac HelloWorld.javacreates the file
HelloWorld.class(assuming, of course, there are
no syntax errors!)
49More On Java Programming
- Regarding running the code
- Remember, Java is interpreted
- It would be more correct to say interpreting the
code but, no one does! - e.g. java HelloWorld.class
- Starts the Java interpreter with the Java
bytecode in the file HelloWorld.class - The interpreter then executes the bytecode one
bytecode instruction at a time
50Discussion Points
- Nested loops pre/post tested?, termination
- Test cases
- Debugging
- Compile time syntax errors
- Run time logic errors
- Algorithm
- Ordered ?
- Terminating ?
- Unambiguous and effective ?
- No! some steps need to be refined (i.e. explained
further)
51Stepwise Refinement
- Recall each step of an algorithm must be
effective. - Stepwise Refinement (aka Top-down Design )
- General idea attack a large problem by dividing
it into smaller pieces - Main algorithm is composed of major logical
steps details of each of these major steps are
given separately, in a module that deals only
with that sub-step. - If necessary, decompose that module into smaller
steps and so on - When to stop? When each individual instruction
is unambiguous and effective. - Terminology for modules subroutines, procedures,
functions, methods (used in Java)
52Stepwise Refinement
- The first (main) algorithm is said to be at the
highest level of abstraction - There may be many levels of abstraction below
this, depending on the problem - Once an algorithm is organized by levels of
abstraction, the details of each logical step can
be in a separate module, each of which has its
own name - Each module represents one task
53Stepwise Refinement
- When stepwise refinement is used, the resulting
algorithm (and, eventually, program) is said to
be modular. - This is something that all programs should be, to
allow for - Ease of design, modification, and correction
- Reuse of modules
- Separate design, writing, and testing of modules
- Information hiding need to know basis
54Stepwise Refinement
- Examples
- The Java Programming Algorithm what would the
modules be? - Create a menu driven algorithm that allows a user
to either calculate the average of three numbers
or calculate the greatest common divisor - What would the modules be for a web browser like
Internet Explorer or Firefox?
55Algorithm vs. Program
- Recall
- An algorithm is not written in any particular
computer language - A computer program expresses an algorithm in a
specific programming language - It should be possible to translate a well-written
algorithm into any programming language. - Advice programmers should make sure that their
algorithm is indeed an algorithm
(ordered, unambiguous, effective, terminating)
before it is translated into a computer program!
(Why?, how?)
56Further Reading
- The following sections from the Java 5.0 Program
Design text supplement these notes nicely - Section 1.7