Starting from:
$30

$24

Lab 6 Solution

Section Readings: 1.1 (Recursion)




Problem 1. (Sum of Integers) Implement the static methods sumIter() and sumRec() in SumOfInts that take an integer argument n and return the sum S(n) = 1 + 2 + 3 + + n, computed iteratively (using a loop) and recursively. The recurrence relation for the latter implementation is

S(n) =
(n + S(n 1) if n 1:


1
if n = 1;












java S um Of In ts 100 5050 5050



Problem 2. (Exponentiation) Implement the static method power() in Power that takes two integer arguments a and b and returns the value of ab, computed recursively using the recurrence relation

ab =
8aab
1 if b is odd;



1


if b = 0;


2
b=2













<(a )if b is even:


:









java Power 3 5 243









Problem 3. (Bit Counts) Implement the static methods zeros() and ones() in Bits that takes a bit string (ie, a string of zeros and ones) s as argument and returns the number of zeros and ones in s, each computed recursively. Hint: First devise an appropriate recurrence relation for the problem.







java Bits 1 0 1 0 0 1 0 0 1 0 0 1 1 1 1 0 0 0 1 0 1 1 1 1 1 zeros = 11 , ones = 14 , total = 25






Problem 4. (String Reversal) Implement the static method reverse() in Reverse that takes a string s as argument and returns the reverse of the string, constructed recursively. Hint: First devise an appropriate recurrence relation for the problem.







java Reverse " a man a plan a canal panama " amanap lanac a nalp a nam a



Files to Submit:




SumOfInts.java



Power.java



Bits.java



Reverse.java


















1 of 1

More products