Question

Recursion Exercises These exercises provide practice with recursion in Java. Objectives Module: To write recursive solutions...

Recursion Exercises

These exercises provide practice with recursion in Java.


Objectives

Module:

  • To write recursive solutions for basic problems that require iteration.
  • To identify and address base cases in a recursive method.


Reminders during development

  • Each of your solutions to the problems below should be in their own method.
  • If a method header is provided for a problem, then your solution should have that exact method header. Any changes to the method header will receive a zero for that problem.
  • You may not use fields in support of any of your methods. Anyone using a field to help write the logic of a method will receive a zero for that problem.
  • Each problem has several test cases, where the method is invoked and there is some type of output shown. You are required to test these cases with your submission. I should be able to run your code once and clearly see where you make the method calls and the expected output.
  • You may write other private recursive methods to support a method that you are required to write. You may not call these methods directly in your tests. You must call the public method described in each problem when testing.


Requirements

  • You should submit a single project with all your work for the six problems you were assigned
  • It should be easy to see each method in your code submission. Any messy or disorganized submissions will be penalized.
  • Any solutions that include any form of loop will not be accepted.
1

Write a recursive method that reports whether a number is prime or not. Recall that a number is prime if it is only divisible by itself and the number one.

Note: Negative numbers, zero and one are not prime by definition. Your method must recognize these values and return a sensible result.

Your method should have the following header:

public boolean isPrime(int candidate)
{
    //do something
}

Test cases:

isPrime(1); //false
isPrime(22); //false
isPrime(59); //true
isPrime(99); //false

2

Write a recursive method that accepts an array of words and returns the longest word found in the array. If the input array is empty then the method should return null. Your method should have the following header:

public String longestWord(String[] words)
{
    //do something
}

Test cases:

longestWord(["and", "as", "abba", "are"]); //abba
longestWord([]); //null
longestWord(["here"]); //here
longestWord(["there", "then", "to", "their", "together"]); //together

0 0
Add a comment Improve this question Transcribed image text
Answer #1

CODE:

public class Recursion
{
   private boolean isPrime(int number,int divisor)
   {
       //Exit condition
       if(divisor == number)
       {
           return true;
       }
      
       boolean result = ((number % divisor) == 0);
      
       if(result)
           return false;
      
       return isPrime(number,divisor + 1);
      
      
   }
   public boolean isPrime(int candidate)
   {
       if(candidate <= 1)
           return false;
      
       return isPrime(candidate,2);
   }
  
   private String maxLengthWord(String[] words,int index,String maxWord)
   {
       if(index == words.length)
           return maxWord;
      
       if(words[index].length() > maxWord.length())
           maxWord = words[index];
      
       return maxLengthWord(words,index + 1,maxWord);
   }
  
  
   public String longestWord(String[] words)
   {
       if(words.length == 0)
           return null;
      
       return maxLengthWord(words,0,words[0]);
   }
  
   public static void main(String[] args)
   {
       Recursion r = new Recursion();
       System.out.println(r.isPrime(1)); //false
       System.out.println(r.isPrime(22)); //false
       System.out.println(r.isPrime(59)); //true
       System.out.println(r.isPrime(99)); //false
      
       String[] strArray1 = new String[]{"and", "as", "abba", "are"};
       System.out.println(r.longestWord(strArray1)); //abba
       String[] strArray2 = new String[0];
       System.out.println(r.longestWord(strArray2)); //null
       String[] strArray3 = new String[]{"here"};
       System.out.println(r.longestWord(strArray3)); //here
       String[] strArray4 = new String[]{"there", "then", "to", "their", "together"};
       System.out.println(r.longestWord(strArray4)); //together
   }
}

OUTPUT:

Add a comment
Know the answer?
Add Answer to:
Recursion Exercises These exercises provide practice with recursion in Java. Objectives Module: To write recursive solutions...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Recursion Exercises These exercises provide practice with recursion in Java. Please add notes if possible. Objectives...

    Recursion Exercises These exercises provide practice with recursion in Java. Please add notes if possible. Objectives Module: To write recursive solutions for basic problems that require iteration. To identify and address base cases in a recursive method. Reminders during development Each of your solutions to the problems below should be in their own method. If a method header is provided for a problem, then your solution should have that exact method header. Any changes to the method header will receive...

  • MUST BE IN JAVA AND USE RECURSION Write a recursive method that returns the number of...

    MUST BE IN JAVA AND USE RECURSION Write a recursive method that returns the number of all occurrences of a given word in all the files under a directory. Write a test program. Use the following header: public static long findInFile(File file, String word)

  • 4. [Tests basic knowledge of recursion] Write a recursive static Java method that accepts an array...

    4. [Tests basic knowledge of recursion] Write a recursive static Java method that accepts an array arr of integers argument returns a list of all permutations of these integers. (A permutation of a sequence of integers is a re-arrangement of the integers. For example, one permutation of 1, 3, 4, 8, 2 is 3, 1, 2, 8, 4.) For this problem, you may assume that the input array contains no duplicate entries. Your method should return an ArrayList of int...

  • Using Java: 1. Recursive Multiplication Write a recursive function that accepts two arguments into the parameters...

    Using Java: 1. Recursive Multiplication Write a recursive function that accepts two arguments into the parameters x and y. The function should return the value of x times y. Remember, multiplication can be performed as repeated addition as follows: 5×6=6+6+6+6+6 2. Recursive findings Write a recursive boolean method named reFinding. The method should search an array for a specified value, and return true if the value is found in the array, or false if the value is not found in...

  • Programming Assignment #7 (Recursion) This assignment is to write some methods that perform simple array operations...

    Programming Assignment #7 (Recursion) This assignment is to write some methods that perform simple array operations recursively. Specifically, you will write the bodies for the recursive methods of the ArrayRecursion class, available on the class web page. No credit will be given if any changes are made to ArrayRecursion.java, other than completing the method bodies Note that the public methods of ArrayRecursion – contains(), getIndexOfSmallest(), and sort() – cannot be recursive because they have no parameters. Each of these methods...

  • PLEASE HELP! Need to understand for upcoming test :( Recursion sure is tough Write a recursive...

    PLEASE HELP! Need to understand for upcoming test :( Recursion sure is tough Write a recursive method (not a complete program) that is passed a string. Your method should return the Boolean constant true if the string has NO occurrences of the letter "A". otherwise should return false

  • Write a method called printReverse() that takes a string and uses recursion to print the contents...

    Write a method called printReverse() that takes a string and uses recursion to print the contents of the string in reverse order. The string itself should not be reversed; it must be left in its original form. The method has the following header:   void printReverse(String s, int i) where s is a reference to the string, and i is an integer parameter that you may use as you see fit. You do not need to code up this method as...

  • JAVA Recursion: For this assignment, you will be working with various methods to manipulate strings using...

    JAVA Recursion: For this assignment, you will be working with various methods to manipulate strings using recursion. The method signatures are included in the starter code below, with a more detailed explanation of what function the method should perform. You will be writing the following methods: stringClean() palindromeChecker() reverseString() totalWord() permutation() You will be using tools in the String class like .substring(), .charAt(), and .length() in all of these methods, so be careful with indices. If you get stuck, think...

  • A java program for this question please! Recursion: A word is considered elfish if it contains...

    A java program for this question please! Recursion: A word is considered elfish if it contains the letters: e, l, and f in it, in any order. For example, we would say that the following words are elfish: whiteleaf, tasteful, unfriendly, and waffles, because they each contain those letters. Write a recursive method called elfish(), that, given a word, tells us whether or not that word is elfish. The signature of the method should be: public static boolean elfish(String word)...

  • Please use public class for java. Thank you. 1. (10 points) Write a method that computes...

    Please use public class for java. Thank you. 1. (10 points) Write a method that computes future investment value at a given interest rate for a specified number of years. The future investment is determined using the formula futurelnvestmentValue numberOfYears 12 investmentAmount X ( monthlyInterestRate) Use the following method header: public static double futurelnvestmentValue( double investmentAmount, double monthlyInterestRate, int years) For example, futureInvestmentValue 10000, 0.05/12, 5) returns 12833.59. Write a test program that prompts the user to enter the investment...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT