lecture 8 of computer science ii recursions instructor: mr.ahmed al astal

9
Lecture 8 of Computer Science II Recursions Instructor: Mr.Ahmed Al Astal

Upload: ferdinand-bailey

Post on 17-Dec-2015

214 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Lecture 8 of Computer Science II Recursions Instructor: Mr.Ahmed Al Astal

Lecture 8 of Computer Science II

Recursions

Instructor: Mr.Ahmed Al Astal

Page 2: 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: Lecture 8 of Computer Science II Recursions Instructor: Mr.Ahmed Al Astal

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: Lecture 8 of Computer Science II Recursions Instructor: Mr.Ahmed Al Astal

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: Lecture 8 of Computer Science II Recursions Instructor: Mr.Ahmed Al Astal

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: Lecture 8 of Computer Science II Recursions Instructor: Mr.Ahmed Al Astal

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: Lecture 8 of Computer Science II Recursions Instructor: Mr.Ahmed Al Astal

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: Lecture 8 of Computer Science II Recursions Instructor: Mr.Ahmed Al Astal

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: Lecture 8 of Computer Science II Recursions Instructor: Mr.Ahmed Al Astal

Page 9

Recursions

ca b

A recursive implementation