Question

Write a main program that runs the following two recursive methods demonstrating that they work. #1) Write a recursive method
#2) Write a recursive method is Palindrome that accepts a String and returns true if it reads the same forwards as backwards.

Please write in java
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Please find the running java code below for both the given problems. Please do comments in case of any issue or more information is needed. Also, if you like my work please give it a thumbs up to encourage. Thank You.

You can use any JAVA compiler to run this file. The comments have also been added for code segments for better understanding of the code. The output screenshots have also been attached for your reference.

Question 1:

The logic in the code has been implemented as per the description in the problem. The file name is Main.java

Here I have implemented writeSquares(), a recursive function that accepts an integer n(taken from user/console) and prints odd squares in decending order followed by even squares in acending order.

Java Source Code:

//program that has writeSquares() recursive method that accepts an integer n and prints odd squares in decending order followed by even squares in acending order
import java.util.Scanner; //for taking the input from the user

//Main class
public class Main {

    //writeSquares() function that returns squares String
    // the function first calls  writeOddSquares() to print odd squares
    // followed by writeEvenSquares() to print even squres
    public static String writeSquares(int n) {

        if (n < 1) //if n is less than 1 then print "nothing"
            return "nothing";
        if (n == 1) //if n is 1 then call writeOddSquares()
            return writeOddSquares(n);
        else //otherwise call first call writeOddSquares() and secondaly call writeEvenSquares();
            return writeOddSquares(n) + writeEvenSquares("", n);
    }
    //writeOddSquares() is a recursive function 
    //that returns a String of  the odd squraes in decending order 
    public static String writeOddSquares(int n) {

        //Base case: if n is 1 return 1
        if (n == 1) {
            return 1 + " ";

        } else if (n % 2 != 0) { //otherwise test if number is odd and return squares
            return n * n + " " + writeOddSquares(n - 1);
        }
        return writeOddSquares(n - 1);
    }

    //writeEvenSquares() is a recursive function 
    //that returns a String of  the even squraes in acending order 
    public static String writeEvenSquares(String s, int n) {

        //Base case: if n is 2 return 4
        if (n == 2) {
            return "4";
        } else if (n % 2 == 0) { //otherwise test if number is even and return squares  
            return writeEvenSquares(s, n - 1) + " " + n * n;
        }
        return writeEvenSquares(s, n - 1);

    }
    //main() function to test the functionality
    public static void main(String[] args) {
        int n; //stores the integer entered by User
        Scanner sc = new Scanner(System.in); //create an object of Scanner class
        System.out.print("Please enter an integer:"); //prompt
        n = sc.nextInt(); //read integer n from user
        System.out.println(writeSquares(n)); //call writeSquares() function and display the result
    } //end of main() function
} //end of Main Class

Output:

When you run the above java code and input value is provided as 11 on the console then output is printed on the console as below-

at Main.writeEvenSquares (Main.java:25) > javac -classpath .:/run_dir/junit-4.12.jar:target/dependency/* -d . Main.java >java

When you run the above java code and input value is provided as 1 on the console then output is printed on the console as below-

> javac -classpath .:/run_dir/junit-4.12.jar:target/dependency/* -d . Main.java >java -classpath .:/run_dir/junit-4.12.jar:ta

--------------------------------------------------------------------------------------------------------------------------------------------------

Question 2:

The logic in the code has been implemented as per the description in the problem. The file name is Main.java

Here I have implemented the isPalindrome(), a recursive function that accepts a String and returns true if String is palindrome otherwise retuns false if it is not palindrome. In the main() function we have also tested the isPalindrome() function functionality by passing String values taken from user and print result either true or false depending on the string.

Source Code:

//program that has isPalindrome() recursive method that accepts a String and returns true if String is palindrome otherwise retuns false if it is not palindrome. In the main() function we test the isPalindrome() by passing string values taken from user and print result.
import java.util.Scanner; //for taking the input from the user
//Main class
class Main {

    //isPalindrome() a recursive function  takes a String 
    //and returns true if the string is palindrome
    //otherwise returns false if String is not palindrome
    public static boolean isPalindrome(String s) { // Base case: if length is 0 or 1 then String is palindrome
        if (s.length() == 0 || s.length() == 1)
            return true;
        //checking for first and last character of String,
        // if they are same then we will do the same thing
        // for a substring with first and last character being removed.
        // and we will carry on this until the condition fails or base case is executed
        if (s.charAt(0) == s.charAt(s.length() - 1))
            return isPalindrome(s.substring(1, s.length() - 1)); //recursive call
        //otherwise return false since palindrome condition gets failed
        return false;
    }
    //main() function to test isPalindrome() function
    public static void main(String[] args) {
        //creating instance sc of Scanner Class to take input from user
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the String for checking palindrome : "); //prompt
        String string = sc.nextLine(); //read String from user/console

        System.out.println(isPalindrome(string)); //calling isPalindrome() function and print result

    }
}

Output:

When you run the above java code and input string is provided as madam on the console then output is printed on the console as below-

> javac -classpath .:/run_dir/junit-4.12.jar:target/dependency/* -d > javac -classpath ./run dir/junit-4.12.jar:target/depend

When you run the above java code and input string is provided as notion on the console then output is printed on the console as below-

>javac -classpath .:/run_dir/junit-4.12.jar:target/dependency/* -d . Main.java >java -classpath .:/run_dir/junit-4.12.jar:tar

Add a comment
Know the answer?
Add Answer to:
Please write in java Write a main program that runs the following two recursive methods demonstrating...
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
  • Those are  JAVA Programs. Please write them in recursions , it requires the methods have to be...

    Those are  JAVA Programs. Please write them in recursions , it requires the methods have to be recursive(I understood how to write them by using for loop). Please don't use any syntax beyond chapter of Recursion. I only covered the materials to recursions and the materials before recursion chapter. Appreciated! #1) Write a recursive method writesquares that accepts an integer n and prints the first n squares with the odd squares in decending order, followed by the even squares in acending...

  • A palindrome is a word, phrase, number, or other sequence of characters which reads the same...

    A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward, such as madam or racecar. Write a recursive method in java that accepts a integer as its argument and returns true if it is palindrome, false otherwise. public class Recursion {                 public static void main(String[] args) {                                 Recursion r = new Recursion();                                 System.out.println(“Is 12321 a palindrome? “+ra.isPalindrome(12321)); //true                 }                 public Boolean isPalindrome(int num){                                 return false;...

  • PLEASE USE MATLAB This is a basic problem that illustrates the concept of strings. A palidrome...

    PLEASE USE MATLAB This is a basic problem that illustrates the concept of strings. A palidrome is a string of characters that is read the same forwards as it is backwards. For example, racecar' is a palindrome; reversing the order of the characters leaves the string unchanged. Write a otherwise. function called isPalindrome that accepts one input and returns one output. The input str is a string of characters, and the output is 1 if str is a palindrome, For...

  • Write a function check palindrome, which takes a string x as argument and which returns True...

    Write a function check palindrome, which takes a string x as argument and which returns True if x is a palindrome, and False otherwise. A palindrome is a word that reads the same backwards as forwards (like for example “racecar”). Your function should be recursive (i.e. call itself) and proceed as follows. 1. If x is a string of length 0 or 1 return True. 2. If the rst and the last letter of x are di erent, return False....

  • Please i need programs in C 32) Write a function that, given a string, a width,...

    Please i need programs in C 32) Write a function that, given a string, a width, and an empty string for output, centers the string in the output, centers the string in the output area. The function is to return 1 if the formating is successful and 0 if any errors, such as string length greater than width, are formed. 35) Write a function called newStrCmp that does the same job as strcmp. The declaration for your functions is to...

  • 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...

  • – Palindrome Game Please write a Java program to verify whether a given word is a...

    – Palindrome Game Please write a Java program to verify whether a given word is a palindrome. You must stop your program when the user enters ‘@’ character as the word. You may write a recursive program to solve this game, but you don’t have to. You may use a stack and/or a queue to solve this game, but you don’t have to. You must run 3 test cases for your program.   Your test case #1 must look as follows:...

  • Write a java program that asks the user to enter an integer. The program should then...

    Write a java program that asks the user to enter an integer. The program should then print all squares less than the number entered by the user. For example, if the user enters 120, the program should display 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, and 100.

  • ***************Fix code recursive function #include <iostream> #include <cctype> #include <string> using namespace std; void printUsageInfo(string executableName)...

    ***************Fix code recursive function #include <iostream> #include <cctype> #include <string> using namespace std; void printUsageInfo(string executableName) { cout << "Usage: " << executableName << " [-c] [-s] string ... " << endl; cout << " -c: turn on case sensitivity" << endl; cout << " -s: turn off ignoring spaces" << endl; exit(1); //prints program usage message in case no strings were found at command line } string tolower(string str) { for(unsigned int i = 0; i < str.length(); i++)...

  • Your program must prompt the user to enter a string. The program must then test the...

    Your program must prompt the user to enter a string. The program must then test the string entered by the user to determine whether it is a palindrome. A palindrome is a string that reads the same backwards and forwards, such as "radar", "racecar", and "able was I ere I saw elba". It is customary to ignore spaces, punctuation, and capitalization when looking for palindromes. For example, "A man, a plan, a canal. Panama!" is considered to be a palindrome....

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