CS 1312 - PowerPoint PPT Presentation

1 / 109
About This Presentation
Title:

CS 1312

Description:

Great idea! if you change. the array size, you need only. change the ... 'Recursion Rocks My World!' Recursion. Let's say you place two rabbits in a hutch. ... – PowerPoint PPT presentation

Number of Views:46
Avg rating:3.0/5.0
Slides: 110
Provided by: ccGa
Category:
Tags: great | let | spin | the | world

less

Transcript and Presenter's Notes

Title: CS 1312


1
CS 1312
  • Introduction to
  • Object Oriented Programming
  • Lecture 3

2
Sound Check
3
Some Final Words on Methods
4
RECALL Three major paradigms for programming
5
Java Methods
  • There exists in Java a single construct, the
    method, for both procedures and functions
  • when a procedure is called for, specify the
    return type void before method name
  • public void printHelloWorld( )
  • System.out.println(Hello World!)
  • // of printHelloWorld
  • Note All methods must have parentheses for
    parameters . . . even if no parameters!

Quick Review
6
Java Methods
  • Single construct for both procedures and
    functions
  • when a function is called for, specify the
  • appropriate return type before method name
  • public float average (float fNum1, float
    fNum2, float fNum3)
  • float fReturnVal
  • fReturnVal
  • (fNum1 fNum2 fNum3)/ 3
  • return (fReturnVal)
  • // of average

Quick Review
7
Method Signatures
The signature of a method consists of the name
of the method and the number and types of formal
parameters to the method. A class may not declare
two methods with the same signature, or a compile
time error occurs. --Java Language
Specification s.8.4.2 Method overloading occurs
when identically named methods have different
signatures. public int getCube(int
iNum) return iNumiNumiNum public
int getCube(float fNum) return
(int)(fNumfNumfNum) public int
getCube(double dNum) return (int)
(dNumdNumdNum)
Quick Review
Quiz Alert!
8
Parameters
  • Unlike Pseudocode, Java only has in parameters.
  • Thus no need to declare in, in/out or out cause
    theyre all IN
  • Parameters do need to be declared just like
    variables
  • public void demo(int i, float x)
  • More about parameters when we discuss objects

9
Where do Methods Go?
Methods (and variables) are contained in Classes,
as either class or instance members. More on
creating classes and objects shortly . . .
Quick Review
class zippy int pin public String yow()
// some code
10
Questions?
11
Announcements
12
On the Subject ofAcademic Misconduct
13
Academic Misconduct
  • Key feature of Ga Tech is validation.
  • Students who cheat damage everyone at this
    institution.
  • You may discuss assignments at a high
    conceptual level.
  • But thats all!
  • Do your own work.
  • Zero level of tolerance

14
Academic Misconduct
  • Cheatfinder is real
  • The lecturer, the TAs, the Program Manager and
    the Deans take this issue very seriously
  • Every term a non-negligible number of students
  • Fail the course
  • Are required to do community service
  • Have an ugly notation on their record

15
Academic Misconduct
  • Questions???

16
Iteration
17
Java Basics Iteration Constructs
  • In Pseudocode, we had a single iteration
    construct, flexible enough to be used in all
    iteration contexts.

Actually (if you were paying attention last
semester) we talked about three kinds of
loops Sentinal Loops Test-Last
Loop N-and-a-half Loops
18
Java Basics Iteration Constructs
  • In Pseudocode, we had a single iteration
    construct, flexible enough to be used in all
    iteration contexts.
  • Java, like most programming languages, does not
    provide a single flexible construct.
  • Instead, Java offers three special case loop
    constructs, each good for a particular context.
  • Do not get accustomed to only one of them and
    try to use it for all situations.
  • To use them wisely, you should consider not only
    how they work, but also when each is best used

19
Java Iteration Constructs While Loops
When repeating steps, people naturally want to
follow the pattern get a value, then process
that value The while loop construct calls for
the unnatural pattern obtain the first loop
control value before entering the loop itself
then, within the loop body, first do the
process steps, then do the get next steps
20
Unnatural?
  • while(You havent gotten to my street)
  • Keep going straight
  • turn right

21
Java Iteration Constructs While Loops
Java example ltget first valuegt while
(condition) ltprocess valuegt ltget next
valuegt
Pseudocode ltget first valuegt loop exitif
NOT(condition) ltprocess valuegt ltget next
valuegt endloop
Pseudocode flavor Sentinal
22
Java Iteration Constructs Do While Loops
Java example do statement
1 ... statement N while
(condition)
Pseudocode loop statement 1
... statement N exitif
(NOT(condition)) endloop
Pseudocode flavor Test Last
23
Java Iteration Constructs For Loops
Java syntax for (ltinitializationgt ltcontinue
ifgtltincrementgt)
Java example int i for (i0 ilt10
i) ltsome statementsgt
Pseudocode i isoftype Num i lt- 0 loop
exitif (i gt10) ltsome statementsgt
i lt- i 1 endloop
24
Secret! A for Loop can be exactly written as a
while loop
  • i 0
  • while (i lt 10)
  • System.out.println(i)
  • i
  • for(i 0 i lt 10 i)
  • System.out.println(i)

This will help you understand the sequence of
operations of a for loop
25
Java Iteration Constructs For Loops
  • Common Problems with For Loops include

for (i0 iltN i)
for (int i0 iltN i)
26
Potential Confusion
  • public class Forex
  • static int i 42
  • public static void main(String args)
  • for(int i0 i lt 5 i)
  • System.out.println(i)
  • System.out.println(i)

27
Output
  • 0
  • 1
  • 2
  • 3
  • 4
  • 42

28
Java Iteration Constructs When to Use
--The term control variable refers to the
variable whose value is tested to determine if
the loop should continue for another iteration or
halt. --For example, variable thisVar,
below while (thisVar lt SOME_CONSTANT) --T
o determine which loop construct is appropriate
for a given situation, ask yourself where does
the control variables value come from?
29
Java Iteration Constructs When to Use
The for loop used when the control variable is
a simple count of the number of iterations,
e.g. create a loop that reads and processes
the next 100 numbers. The while
loop used when the control variable has a value
that already exists and is simply obtained by
the loop. e.g. create a loop that reads in
numbers and processes them until it
reads in a 100. The do-while loop used when
the control variables value must be calculated
by the loop itself. e.g. create a loop that
reads in numbers until their sum is
greater than 100.
30
Java Iteration Constructs Review
Which loop construct would you use if...
You need to perform a series of steps exactly N
times?
You need to traverse a linked list of unknown
size, and stop when you find a certain value?
You need to perform a series of steps at least
once, and continue performing these steps for an
an unknown number of times
31
Iteration Reiteration
  • Three kinds of iteration
  • for (.........) ... loops
  • Fixed number of iterations
  • while (...) ... loops
  • Iteration condition evaluated in advance
  • do ... while (...) loops
  • Iteration condition evaluated in the loop

32
Questions?
33
Arrays of Primitives
  • The Idea
  • Same concepts you know from Pseudocode
  • A few differences in implementation
  • Java array declaration
  • ltelemTypegt ltarrIDgt new ltelemTypegtltsizegt
  • e.g. to declare an array of ten ints for
    storing numerical grades...
  • int iGradeArray new
    int10
  • Array declaration error
  • using parentheses, not brackets, e.g.,
  • int iGradeArray new
    int(10)

34
Details
  • The odd looking syntax is because arrays (even
    arrays of primitives) are objects.
  • We'll explain in detail once we get to objects...
  • int iGradeArray new int10
  • int iGradeArray new int10

35
Arrays
  • Example
  • declare iGradeArray of 10 ints
  • initialize all 10 values to 0

Great idea! if you change the array size, you
need only change the instantiation.
  • Notes
  • Arrays know their own length
  • length is a field, not a method
  • Arrays are statically sized you cannot change
    the length after declaration.
  • All arrays are objects, thus you must declare a
    reference, and instantiate it, and initialize it

36
  • More Notes
  • Array indices begin at 0, not at 1
  • So, length is one greater than iMAX_INDEX
  • Thus, an error if you do

Arrays
int iGradeArray new int10 int i for
(i1 i lt iGradeArray.length i)
iGradeArrayi 0 // for loop
  • Code above attempts to access elements 1..10
  • But... you have indices 0..9
  • So it misses the 1st element (which is at index
    0) it tries to go past 10th element
    (which is at index 9)

37
Questions?
38
Sample Quiz Problem
Given an array of ints, return the index of the
largest element. Use the code below.
public int getLargestIndex(int iArray)
/ YOUR CODE GOES HERE /
39
Sample Quiz Problem
Given an array of ints, return the index of the
largest element. Use the code below.
public int getLargestIndex(int iArray)
int iLargest -9999 int iCounter for
(iCounter 0 iCounter lt iArray.length
iCounter)
if (iLargest lt iArrayiCounter)
iLargest iArrayiCounter
return iLargest // getLargestIndex
Does this work?
40
Sample Quiz Problem
Given an array of ints, return the index of the
largest element. Use the code below.
public int getLargestIndex(int iArray)
int iLargest -9999 int iCounter for
(iCounter 0 iCounter lt iArray.length
iCounter)
if (iLargest lt iArrayiCounter)
iLargest iArrayiCounter
return iLargest // getLargestIndex
What if all the values are less than -9999
41
Sample Quiz Problem
Given an array of ints, return the index of the
largest element. Use the code below.
public int getLargestIndex(int iArray)
int iLargest iArray0 int iCounter for
(iCounter 0 iCounter lt iArray.length
iCounter)
if (iLargest lt iArrayiCounter)
iLargest iArrayiCounter
return iLargest // getLargestIndex
How about this?
42
Sample Quiz Problem
Given an array of ints, return the index of the
largest element. Use the code below.
public int getLargestIndex(int iArray)
int iLargest iArray0 int iCounter for
(iCounter 1 iCounter lt iArray.length
iCounter)
if (iLargest lt iArrayiCounter)
iLargest iArrayiCounter
return iLargest // getLargestIndex
Why not start out iCounter at 1, and not 0 like
most for loops?
43
Sample Quiz Problem
Given an array of ints, return the index of the
largest element. Use the code below.
public int getLargestIndex(int iArray)
int iLargest iArray0 int iCounter for
(iCounter 1 iCounter lt iArray.length
iCounter)
if (iLargest lt iArrayiCounter)
iLargest iArrayiCounter
return iLargest // getLargestIndex
Now it should be perfect!
44
Sample Quiz Problem
Given an array of ints, return the index of the
largest element. Use the code below.
NOTE THIS!
public int getLargestIndex(int iArray)
int iLargest iArray0 int iCounter for
(iCounter 1 iCounter lt iArray.length
iCounter)
if (iLargest lt iArrayiCounter)
iLargest iArrayiCounter
return iLargest // getLargestIndex
Test taking is about READING THE DIRECTIONS
45
Sample Quiz Problem
Whats the solution? This is a good problem to
work out on your own. We dont want the largest
VALUE, we instead want the INDEX of the largest
value.
46
Lessons Learned
Read the question carefully. Dont fall into
habits (e.g., all for loops must start with
the counter at 0). Dont make assumptions about
input data (e.g., -99999 is NOT a good initial
value). Trace your code watch for simple gt, lt
errors.
47
Questions?
48
The Road Ahead
Today
  • Recursion
  • Classes and Objects
  • Constructors
  • Object References
  • Parameters

49
A Question
How many people here dont like recursion?
Why not?
A Promise By the end of this lecture, you will
say Recursion Rocks My World!
50
Recursion
Lets say you place two rabbits in a hutch.
Whats going to happen?
51
Two Months Later...
original rabbits
new rabbits
If it takes two months for rabbits to reach
maturity, in two months youll have one
productive pair and one (brand new)
non-productive pair. (This assumes all rabbits
live up to their reputation.)
52
The rabbits keep at it.
1 month old
0 months old
The next month, you get another pair . . .
53
Suppose
What if The rabbits always had two offspring,
always male and female Rabbits
always reached maturity in two months No
rabbit dies. How many pairs of rabbits do you
have in a year?
1
2
3
54
Hare Raising Story
Start
55
Pairs of Rabbits
See a pattern yet?
56
Lets Take Another Example
Instead of rabbits, lets use geometry. Draw a
square of size 1. Rotating 90 degrees, add to it
a square of size 1. Rotating 90 degrees again,
add a square of size 2. Again, rotate and add a
square of size 3, and so on. Keep this up for
the sequence we noted in the table
1, 1, 2, 3, 5, 8, 13, 21, . . . , What do you
see?
57
1
58
1
59
2
60
3
61
5
62
8
63
13
64
21
65
(No Transcript)
66
Does this look familiar?
67
Its not just about rabbits.
68
The Truth is Out There
69
See the pattern?
Its the Fibonacci Sequence.
We used brute force to find the progression 1,
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ... , It
turns out this pattern is repeated in many
places sea shells, sun flowers, pine cones, the
stock market, bee hives, etc.
70
Writing the Formula
Given 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,
144, ... , Can we write this as a formula for
any number, n?
But lets be honest. Were not as smart as
him. But thats OK. We can code.
71
What If You Cant Find the Formula?
Which one would your rather code and debug? For
some problems, there might not exist a formula,
and recursion is your only option.
Suppose you didnt know
You could take Math 3012 or you could instead
manage with
Fib(n) Fib(n-1) Fib(n-2), Fib(0) 0 Fib(1)
1
(The value at any given place is the sum of the
two prior values.)
72
Recursive Fibonacci
We have our general rule
Fib(n) Fib(n-1) Fib(n-2), Fib(0) 0 Fib(1)
1
We can say a few things about it Its defined
recursively (duh). It has a terminal condition
(AHA!) It can be determined and calculated
(addition).
1
2
3
73
Coding Fibonacci
public class FibTest public static int fib
(int num) // FibTest
What do we know to start with? We know that we
need a method that return the Fibonacci value for
a number at a given position. This suggests a
method that gives and gets an int
74
Coding Fibonacci
public class FibTest public static int fib
(int num) if (num 0) return
0 // FibTest
Whats the FIRST thing we do with a recursive
method? We plan on how it will terminate! We
know one special case for the Fibonacci
sequence F(0) 0
75
Coding Fibonacci
public class FibTest public static int fib
(int num) if (num 0) return 0 else
if (num 1) return 1 // FibTest
We also know a second special case that could
terminate our recursion F(1) 1.
76
Coding Fibonacci
public class FibTest public static int fib
(int num) if (num 0) return 0 else
if (num 1) return 1 else return
fib(num-1) fib(num-2) // FibTest
The last part of our formula is merely F(n)
F(n-1) F(n-2)
77
Coding Fibonacci
public class FibTest public static int fib
(int num) if (num 0) return 0 else
if (num 1) return 1 else return
fib(num-1) fib(num-2) // FibTest
Is this safe? What if someone passed in 0 to our
method? What happens? What if they passed in 1?
78
Coding Fibonacci
public class FibTest public static int fib
(int num) if (num 0) return 0 else
if (num 1) return 1 else return
fib(num-1) fib(num-2) public static
void main(String args) for (int i0 i lt 10
i) System.out.println (fib(i)) //
FibTest
It is our responsibility to write a main to
test this method.
79
Coding Fibonacci
public class FibTest public static int fib
(int num) if (num 0) return 0 else
if (num 1) return 1 else return
fib(num-1) fib(num-2) public static
void main(String args) for (int i0 i lt 10
i) System.out.println (fib(i)) //
FibTest
Are we done? What about negative numbers? More
work is needed
80
Recursion Review
So far, weve seen that for recursive
behavior 1) Recursion exists in all of
nature. 2) Its easier than memorizing a
formula. Not every problem has a formula, but
every problem can be expressed as a series of
small, repeated steps. 3) Each step in a
recursive process should be small, calculable,
etc. 4) You absolutely need a terminating
condition.
81
Honesty in Computer Science
1. To make life easy the typical examples given
for recursion are factorial and the Fibonacci
numbers. 2. Truth is the Fibonacci is a horror
when calculated using normal recursion and
theres not really any big advantage for
factorial. 3. So why all the fuss about
recursion? 4. Recursion is absolutely great when
used to write algorithms for recursively defined
data structures like binary trees. Much easier
than iteration! 5. Recursion is excellent for
any divide conquer algorithm like...
82
One More Example
Suppose we wanted to create a method that
solve Pow(x, y) xy
In other words, the method returned the value of
one number raised to the power of another
public static double pow (double
value, int exponent)
83
Planning the Method
Unlike the Fibonacci example, our mathematical
formula is not the complete answer. Pow(x, y)
xy Were missing some termination
conditions. But we know
x1 x x0 1
So we could use these as our terminating
condition.
84
Attempt 1
public static double pow(double value, int
exponent) if (exponent 0) return
1D
Always, always start with some sort of
terminating condition. We know any
number raised to the zero power is one.
85
Attempt 1
public static double pow(double value, int
exponent) if (exponent 0) return
1D else if (exponent 1) return
value
... and any number raised to the power of one is
itself.
86
Attempt 1
public static double pow(double value, int
exponent) if (exponent 0) return
1D else if (exponent 1) return
value else return value pow (value,
exponent--)
For all other values, we can return the number
times the recursive call, using our exponent as a
counter. Thus, we calculate 26 222222
87
Attempt 1
public static double pow(double value, int
exponent) if (exponent 0) return
1D else if (exponent 1) return
value else return value pow (value,
exponent--)
When we run this, however, bad things happen.
The program crashes, having caused a stack
overflow. How can we solve this?
88
Attempt 1
public static double pow(double value, int
exponent) if (bDEBUG) System.out.println
(Entering with value , and exp
exponent) if (exponent 0)
return 1D else if (exponent 1)
return value else return value
pow (value, exponent--)
We could post to the newsgroup and wait it out,
or pester our TA. Or, we can TAKE CHARGE OF
THE SITUATION. Gather information. Put in
debug statements.
89
Attempt 1
public static double pow(double value, int
exponent) if (bDEBUG) System.out.println
(Entering with value , and exp
exponent) if (exponent 0)
return 1D else if (exponent 1)
return value else return value
pow (value, exponent--)
DOH!
Our debug statement tells us that the exponent
is never being decreased. Evidently, the
exponent-- line is not being evaluated before
the recursive call takes place. As it turns out,
the post-decrement operator -- is the problem.
90
Attempt 1
public static double pow(double value, int
exponent) if (exponent 0) return
1D else if (exponent 1) return
value else exponent exponent -
1 return value pow (value, exponent)

We decide that typing one extra line takes less
time than debugging such a subtle error. Things
are working now.
91
Do I Have to Use Recursion?
public static double pow(double value, int
exponent) if (exponent 0) return
1D else if (exponent 1) return
value else exponent exponent -
1 return value pow (value, exponent)

How many would have preferred to do this with a
for loop structure or some other iterative
solution? How many think we can make our
recursive method even faster than iteration?
92
Nota Bene
Our power function works through brute force
recursion. 28 2 2 2 2 2 2 2
2 But we can rewrite this brute force solution
into two equal halves 28 24 24 and 24
22 22 and 22 21 21 and anything to the
power 1 is itself!
93
And here's the cool part...
  • 28 24 24
  • Since these are the same we don't have to
    calculate them both!

94
AHA!
So only THREE multiplication operations have to
take place
28 24 24 24 22 22 22 21 21
So the trick is knowing that 28 can be solved by
dividing the problem in half and using the result
twice!
95
"But wait," I hear you say!
  • You picked an even power of 2. What about our
    friends the odd numbers?
  • Okay we can do odds like this
  • 2odd 2 2 (odd-1)

96
"But wait," I hear you say!
  • You picked a power of 2. That's a no brainer!
  • Okay how about 221
  • 221 2 220 (The odd number trick)
  • 220 210 210
  • 210 25 25
  • 25 2 24
  • 24 22 22
  • 22 21 21

97
"But wait," I hear you say!
  • You picked a power of 2. That's a no brainer!
  • Okay how about 221
  • 221 2 220 (The odd number trick)
  • 220 210 210
  • 210 25 25
  • 25 2 24
  • 24 22 22
  • 22 21 21

That's 6 multiplications instead of 20 and it
gets more dramatic as the exponent increases
98
The Recursive Insight
If the exponent is even, we can divide and
conquer so it can be solved in halves. If the
exponent is odd, we can subtract one, remembering
to multiply the end result one last time. We
begin to develop a formula Pow(x, e) 1,
where e 0 Pow(x, e) x, where e 1
Pow(x, e) Pow(x, e/2) Pow(x,e/2), where e
is even Pow(x, e) x Pow(x, e-1), where
e gt 1, and is odd
99
Solution 2
public static double pow (double value, int
exponent) if (exponent 0) return
1D else if (exponent 1) return
value
We have the same base termination conditions as
before, right?
100
Solution 2
public static double pow (double value, int
exponent) if (exponent 0) return
1D else if (exponent 1) return
value else if (exponent 2 0)
101
Solution 2
public static double pow (double value, int
exponent) if (exponent 0) return
1D else if (exponent 1) return
value else if (exponent 2 0)
Dont like the mod operator? Get used to it. The
alternative is something mutually recursive and
wacky, like this
public static int isOdd(int num) if (num0)
return 1 else return
isEven(num-1) public static int isEven(int
num) if (num0) return 0 else
return isOdd(num-1)
102
Solution 2
public static double pow (double value, int
exponent) if (exponent 0) return
1D else if (exponent 1) return
value else if (exponent 2 0)
That mod operator is starting to look a lot
better, eh? It merely tests if the number is
evenly divided by two.
public static int isOdd(int num) if (num0)
return 1 else return
isEven(num-1) public static int isEven(int
num) if (num0) return 0 else
return isOdd(num-1)
103
Solution 2
public static double pow (double value, int
exponent) if (exponent 0) return
1D else if (exponent 1) return
value else if (exponent 2 0)
exponent exponent / 2
We next divide the exponent in half.
104
Solution 2
public static double pow (double value, int
exponent) if (exponent 0) return
1D else if (exponent 1) return
value else if (exponent 2 0)
exponent exponent / 2 double half pow
(value, exponent)
We recurse to find that half of the brute
force multiplication.
105
Solution 2
public static double pow (double value, int
exponent) if (exponent 0) return
1D else if (exponent 1) return
value else if (exponent 2 0)
exponent exponent / 2 double half pow
(value, exponent) return half
half
And return the two halves of the
equation multiplied by themselves
106
Solution 2
public static double pow (double value, int
exponent) if (exponent 0) return
1D else if (exponent 1) return
value else if (exponent 2 0)
exponent exponent / 2 double half pow
(value, exponent) return half half
else exponent exponent - 1
If the exponent is odd, we have to reduce it by
one . . .
107
Solution 2
public static double pow (double value, int
exponent) if (exponent 0) return
1D else if (exponent 1) return
value else if (exponent 2 0)
exponent exponent / 2 int half pow
(value, exponent) return half half
else exponent exponent - 1
double oneless pow (value, exponent)
And now the exponent is even, so we can
just recurse to solve that portion of the
equation.
108
Solution 2
public static double pow (double value, int
exponent) if (exponent 0) return
1D else if (exponent 1) return
value else if (exponent 2 0)
exponent exponent / 2 int half pow
(value, exponent) return half half
else exponent exponent - 1
double oneless pow (value, exponent)
return oneless value
We remember to multiply the value returned by
the original value, since we reduced the
exponent by one.
109
Recursion vs. Iteration
Those of you who voted for an iterative solution
are likely going to produce O(N) In a
Dickensian world, you would be fired for
this. While those of you who stuck it out with
recursion are now looking at
O(log2n) For that, you deserve a raise.
110
STOP
Absolutely CRITICAL point coming up
111
Questions?
112
(No Transcript)
Write a Comment
User Comments (0)
About PowerShow.com