Algorithms代写 | Recursive Algorithms

0 Comments

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 recursiveProblemalgrithms. 1 – Recursive Exponentiation  

Write a recursive function power(base, exponent) that, when invoked, returnsbaseexponent For example, 34 would be calculated by the call power(3,4) which would return 81. You may assume base > 0 and exponent ≥ 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) = [your function’s output] power(2,10) = [your function’s output] power(8, 5) = [your function’s output] Problem 2 – Sum the Sequence   Write a recursive function sum(n) which returns the sum of the integers from n through 0. You may assume n ≥ 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) = [your function’s output] sum(5) = [your function’s output]sum(100) = [your function’s output]Problem 3 – Sum the Digits   Write a recursive function sumTheDigits(n) which returns the sum of the digits in integer n. You may assume n ≥ 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 I’m 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. You’ll 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) = [your function’s output] sumTheDigits(123) = [your function’s output]

sumTheDigits(90160) = [your function’s output]

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.

Comments