lecture3 - Outline: * Nature of recursion * Recursive...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Sheet1 Page 1 Outline: * Nature of recursion * Recursive functions * While, do and for loops * Tail recursion ++++++++++++++++++++++++++++++++++++++++++++++++ What if you needed to count the "1" bits in the binary representation of a non-negative number? Well, there are no "1" bits in the number zero. That's our base case. To figure out the rest of the non-negative integers, lets think about the representation: there are 32 bits, from "most" to "least" significant. The value of the number is lsb + 2*(2nd-least) + 4*(3rd-least) + 8*(4th-least) + . .. Given this representation, here are two facts. 1: If N is odd, its least significant bit is 1, otherwise it is zero. 2: An even number divided by two has the same number of 1s. Dividing N by two is the equivalent of shifting its bits one to the right: the least significant gets thrown away, and the most significant is filled with a zero. Given these facts, here's a recursive definition of numOnes: numOnes(N) == 0 if N == 0 (base case) == numOnes(N/2) if N>0, N is even (inductive step) == 1 + numOnes((N-1)/2) if N>0, N is odd (inductive step) Write a recursive version of numOnes. ++++++++++++++++++++++++++++++++++++++++++++++++ Recursion is a mechanism for repetitive evaluation. There are three additional mechanisms in C++: while loops, do loops, and for loops. A while loop has the following syntax: while (<boolean-condition>) <body-statement> On entry to the loop, the condition is evaluated. If the condition is true the body is executed. At the end of the body, control passes
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Sheet1 Page 2 back to the beginning of the loop, and the condition is re-evaluated. The example we've seen so far is factorial: int factorial(int x) // REQUIRES: x>=0 { int result = 1 while (x) { result *= x-- } return result } > This loop has an interesting potential problem. What is it? Here's another example of a while loop, that you might find in, say, a web server: while (1) { request r = getRequest() sendResponse(r) } > When does this loop terminate? In addition to "while" loops, one can write "do" loops, where the
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 16

lecture3 - Outline: * Nature of recursion * Recursive...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online