Instructions

User Manual:

Open the PDF directly: View PDF PDF.
Page Count: 2

Lab 2 Recursive Algorithms
For this lab you will implement 3 different recursive algorithms. Create a single file called
lab2.cpp which includes main() and all the functions required to implement the 3 recursive
algorithms.
Problem 1 Recursive Exponentiation
Write a recursive function power(base, exponent) that, when invoked, returns
baseexponent
For example, 34 would be power(3,4) would return 81. Assume the exponent is an integer
greater than or equal to 0.
Your base case is base0 = 1.
Your recursion step will use the relationship baseexponent = base * baseexponent -1
Use main() to call power() 3 times and show the following output to the console:
power(10,0) = 1
power(2,10) = 1024
power(8, 5) = 32768
Problem 2 Sum the Sequence
Write a recursive function sum(n) which returns the sum of the integers from n through 0.
Assume n is an integer greater than or equal to 0.
For example, sum(4) calculates 4 + 3 + 2 + 1 + 0 and returns 10. sum(0) returns 0.
Use main() to call sum() 3 times and show the following output to the console:
sum(0) = 0
sum(5) = 15
sum(10) = 55
Problem 3 Sum the Digits
Write a recursive function sumTheDigits(n) which returns the sum of the digits in integer
n. Assume n is an integer greater than or equal to 0.
For example, sumTheDigits(5129) calculates 5 + 1 + 2 + 9 and returns 17. For any n less
than 10 the original number is returned. For instance, sumTheDigits(5) returns 5.
Hint: While Im sure there are different solutions, consider pulling off the smallest digit first.
For instance, given the integer 5129, first pull off 9 leaving you with 5120. Then convert 5120 to
512. Youll need to use the remainder operator (%) to do this.
Use main() to call sumTheDigits() 3 times and show the following output to the
console:
sumTheDigits(3) = 3
sumTheDigits(123) = 6
sumTheDigits(90160) = 16
Turn In
Your lab2.cpp file should now have main() plus the 3 recursive functions. main() should
still print out all the information described above. Place a comment with your name at the top
of lab2.cpp and upload only your lab2.cpp file prior to the due date.

Navigation menu