user6179055
user6179055

Reputation:

Printing String in reverse using three pre-given methods?

I need to write a printBackwards() method, using three pre-given methods first, rest and length. printBackwards() method needs to take String as a parameter and prints each letter of that string on the console, but each letter needs to be printed on new line and in reverse order. So if the String is House, the output should be:

e
s
u
o
H

In this exercise, we should use recursion and if-else statements. No arrays, no other (familiar) String method, no while and for loop.

I have done a little bit, I know it is not correct, but that is how much I managed to do. I dont understand how to write code so the method can return letters before letter e. How to use recursion here ?

public class Recurse {

    public static void main(String args[]){

        System.out.println(printBackwards("House"));

    }

    //printBackward: takes a String as a parameter and prints letters of the String, 
    // one on each line, but backwards
    public static String printBackwards(String s){
        if (length(s) == 1){
            return s;
        } else {
            return printBackwards(rest(s));
        }   
    }   


    // first: returns the first character of the given String
    public static char first(String s) {
        return s.charAt(0); 
    }

    // last: returns a new String that contains all but the
    // first letter of the given String
    public static String rest(String s) {
        return s.substring(1, s.length());
    }

    // length: returns the length of the given String
    public static int length(String s) {
        return s.length();
    }
}

Upvotes: 0

Views: 78

Answers (2)

Slavik Meltser
Slavik Meltser

Reputation: 10381

First of all you need to print the output within the printBackwards function, so the main will look like this:

public static void main(String args[])
{
    printBackwards("House");
}

Second, is the way recursion works. If you want it to be executed in the ascending order, you should do stuff before the self function call. Otherwise, in case of descending execution order, you code should be executed after the self calling function. These are the basic principles of the recursion function.

In this case, let's try to build the answer.
First, we need to handle the stop condition, which should be always written before the self calling function. The best and most common stop condition, is to reach to the end of something, in this case it is when we get an empty string, in all other cases we need to call the self function with a slight of a change, in this case it will be providing the rest of the string to the function:

if ( !length(s) )
{
    //stop the recursion
    return;
}
else 
{
    printBackwards(rest(s));
}

When you reach the stop recursion statement, from this point and on, it will close all the opened self function executions, therefor will go backward.
This is the perfect state of what we need to achieve, print the letters backward and because on each state of the printBackwards execution, we have sliced the string a bit from the left letters, it means that the first letter is the one we need.
For example, in case of the string House the last call of the printBackwards function will be when the s variable will hold the e value, because it is one stem from being cut-off to an empty string, when we reach the stop condition. In this case we want to print it out, but in the self call before this one, the s variable will hold the value se, because it is one step before cutting the first letter. So, we not want to print the whole value, but only the first letter of it, like this:

System.out.println(first(s));

Combining everything together, will result the following implementation:

public static String printBackwards(String s)
{
    if ( !length(s) )
    {
        //stop the recursion
        return;
    }
    else 
    {
        printBackwards(rest(s));
        System.out.println(first(s));
    }
}

Hope, I explained it clearly.

Good luck!

Upvotes: 0

Bohemian
Bohemian

Reputation: 425258

Because this is a homework question, I'll leave as much as possible to you, so you learn.

Consider these two facts:

  1. You must print the first character after you have printed the rest
  2. If the string is empty, print nothing

Use these two facts are enough to build a recursive method.

Point 2. is the terminating condition. It's best to code this first.
Point 1. is the main method body, where printing the rest is done using recursion

Once you have your terminating condition and your recursive structure (often, a pre-order or a post-order operation), you can build a recursive method.

Note also the name of the method printBackwards() (not backwards()). That is, the method does the printing; it doesn't return the String backwards.

So, translating the above into pseudo-code (which in this case is practically the code):

  1. if the string is empty do nothing
  2. call self with the rest of the string
  3. print the first character

Upvotes: 2

Related Questions