lecture 8 of computer science ii recursions instructor: mr.ahmed al astal
TRANSCRIPT
Lecture 8 of Computer Science II
Recursions
Instructor: Mr.Ahmed Al Astal
Page 2
Recursions
ca b
Recursions
Recursion is a programming technique in which a method (function) calls itself.
Recursion is another way to achieve repetition, which occurs when a function calls itself.
Page 3
Recursions
ca b
The Factorial function
let us begin with a simple example of computing the value of the factorial function.
Page 4
Recursions
ca b
The Factorial function
In general, for a positive integer n, we can define factorial(n) to be n·factorial(n − 1).
Page 5
Recursions
ca b
A Recursive Implementation of the Factorial Function
let us begin with a simple example of computing the value of the factorial function.
Page 6
Recursions
ca b
Advantage of using recursion?
What is the advantage of using recursion?
For some problems, however, a recursive implementation can be significantly simpler and easier to understand than an iterative implementation.
Such an example is Drawing an English Ruler.
Page 7
Recursions
ca b
Drawing an English Ruler !
Three sample outputs of the ruler-drawing function: (a)a 2-inch ruler with major tick length 4;(b) (b) a 1-inch ruler with major tick length 5;(c) (c) a 3-inch ruler with major tick length 3.
Page 8
Recursions
ca b
A Recursive Approach to Ruler Drawing
consists of three functions.: The main function drawRuler(): draws the entire ruler. Its arguments are the total
number of inches in the ruler, nInches, and the major tick length, majorLength.
The utility function drawOneTick(): draws a single tick of the given length. It can
also be given an optional integer label, which is printed if it is nonnegative.
The recursive function drawTicks(): which draws the sequence of ticks within
some interval. Its only argument is the tick length associated with the interval's
central tick.
Page 9
Recursions
ca b
A recursive implementation