Question: How can I complete these tasks through Java? Lab 4. Recursion cardio Write a class RecursionCardio in RecursionCardio.java. Then write methods for each exercise within
How can I complete these tasks through Java?


Lab 4. Recursion cardio Write a class RecursionCardio in RecursionCardio.java. Then write methods for each exercise within this class. You will need to write your own test cases to ensure your code works. Exercise 1 The sum to the first n natural numbers is Sn=1+2+3++n. Write two versions of the function. The first version, sumIter (int n ), uses a loop to calculate the sum to n and return the result. The second version, sumRecur (int n ), uses recursion to calculate the sum to n and return the result. Hint: - The sum to the 1st natural number is just 1. - The sum to the nth natural number is n+ the sum to the (n1) st natural number. - What other recursive math problem is this similar to? Exercise 2 We have a number of bunnies and each bunny has two big floppy ears. We want to compute the total number of ears across all the bunnies recursively (without loops or multiplication). Define your method as: bunnyEars (int n ) bunnyEars (0) 0 bunnyEars (1) 2 bunnyEars (2)4 We have bunnies standing in a line, numbered 1,2, The odd bunnies (1,3,..)havethe normal 2 ears. The even bunnies (2,4,..)wellsayhave3 ears, because they each have a raised foot. Recursively return the number of "ears" in the bunny line 1, 2,.. n (without loops or multiplication). Define your method as: bunnyEars2(int n ) bunnyEars2 () bunnyEars2(1) 2 bunnyEars2 2(2)5 Exercise 4 Given a non-negative int n, return the sum of its digits recursively (no loops). Note that mod (\%) by 10 yields the rightmost digit (126\% 10 is 6 ), while divide (/) by 10 removes the rightmost digit (126/10 is 12). Define your method as: sumDigits(int n ) sumDigits (126)9 sumDigits (49)13 sumDigits (12)3
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
