Download presentation
Presentation is loading. Please wait.
Published byFerdinand Bailey Modified over 9 years ago
1
Lecture 8 of Computer Science II Recursions Instructor: Mr.Ahmed Al Astal
2
Page 2 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.
3
Page 3 Recursions The Factorial function let us begin with a simple example of computing the value of the factorial function.
4
Page 4 Recursions The Factorial function In general, for a positive integer n, we can define factorial(n) to be n·factorial(n − 1).
5
Page 5 Recursions A Recursive Implementation of the Factorial Function let us begin with a simple example of computing the value of the factorial function.
6
Page 6 Recursions 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.
7
Page 7 Recursions 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.
8
Page 8 Recursions 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.
9
Page 9 Recursions A recursive implementation
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.