Axwell Smith
Axwell Smith

Reputation: 57

Print recursively without any loops

Didn't find any other post like this so i had to ask. It is easy to print anything... but when you're not allowed to use iterative methods then things get tricky.

My problem is that i have two methods in one class. This class has a string that should be printed in reverse.. simple with iterative methods but not when char and int gets in the way,

I have tried to count the amout of integers to the amout of char in a string and then use the other method to take that same string and count of int to print it out in reverse.

NOTE: Need these two methods with string and int as parameters.

What am i doing wrong?

public class PrintRecursive {
private static int j;

public static void main(String[] args) {

    String str = "Hello Everyone!";

    print(str, 0);
    System.out.println(); // Line break
    printReverse(str, 0);
}

private static void printReverse(String str, int i) {
    char ch = (char) i;
    if (ch == ' ') {

    } else
        while (str.contains(str)) {
            i += str.charAt(ch);
        }
}

private static void print(String str, int i) {

    while (str.equals(i)) {
        System.out.println(str.charAt(j--));
    }
}

}

Outcome:

Hello Everyone! !enoyrevE olleH

ALSO: Note that i guess that i should be talking to the methods directly instead of my "private int j".

My code atm is not recursive!!!!!!! But i want it to be but i cannot figure out a way of doing so.

Upvotes: 2

Views: 366

Answers (3)

Sweeper
Sweeper

Reputation: 270770

You can do something like this:

public static void main(String[] args) {
   printStringInReverse("Hello", "Hello".length() - 1);
}

public static void printStringInReverse(String s, int x) {
    if (x < 0) {
        return;
    }
    System.out.print(s.charAt(x));
    printStringInReverse(s, x - 1);
}

Note that I start the method with if (x < 0). This is a "base case", the condition that stops the recursion. Then I print the char at index x, and call the method again, but decrementing x. This means that the next call will print the character before.

In fact, this method don't need to have an int parameter:

public static void printStringInReverse(String s) {
    if (s.equals("")) {
        return;
    }
    System.out.print(s.charAt(s.length() - 1));
    printStringInReverse(s.substring(0, s.length() - 1), x);
}

The second approach is more similar to how recursion is used in functional languages like Haskell.

Next time you are asked to write a recursive method, here are some tips:

  • think of the base case(s). What are the cases where you don't need to call the method again?
  • If it is not one of the base cases, do part of the job with part of the input
  • Call the method itself and pass the rest of the input.
  • Keep in mind that you want the input to be reduced to one of the base cases.

Upvotes: 1

Chris Gong
Chris Gong

Reputation: 8229

A few issues here. First, in your print method, you start off by comparing a string to an integer in your while loop condition. Also, inside your while loop, you decrement a variable j when I believe you should be using variable i here since it's being passed in. So this is probably what you were trying to achieve with print,

private static void print(String str, int i) {
    while (i < str.length()) {
        System.out.print(str.charAt(i++));
    }
}

Now with printReverse, you start off by casting the int variable i that is passed in to a char and compare that to ' '. There's no point to doing this because any valid integer passed in will never equal ' ' after a char cast. I think what you meant to do in this method is pretty much the same thing as print but in reverse. Therefore, all you would need to change is the while loop and the print statement,

private static void printReverse(String str, int i) {
    while (i < str.length()) {
        System.out.print(str.charAt(str.length() - i++ - 1));
    }
}

Note that if you want to this recursively, you need to establish a base case and a recursive call to your function. For example with print you can make the base case the same thing as the while loop condition from above, stop calling print when i >= str.length(), and the call to the method itself can be made after you've printed out the character at index i while simultaneously incrementing i,

private static void print(String str, int i) {
    if (i >= str.length()){
        return;
    }
    System.out.print(str.charAt(i++));
    print(str, i);
}

The same logic can be applied for printReverse,

private static void printReverse(String str, int i) {
    if (i >= str.length()) {
        return;
    }
    System.out.print(str.charAt(str.length() - i++ - 1));
    printReverse(str, i);
}

Upvotes: 1

kske
kske

Reputation: 138

A recursive approach (where one letter is printed in each recursion step) could look like this:

private static void print(String s, int i) {
    if(i == s.length() - 1)   
        System.out.println(s.charAt(i));
    else {
        System.out.print(s.charAt(i));
        print(s, i+1);
    }
}

private static void printReverse(String s, int i) {
    if(i == 0)
        System.out.println(s.charAt(0));
    else {
        System.out.print(s.charAt(i));
        printReverse(s, i-1);
    }
}

You would call it as follows:

public static void main(String[] args) {
    print("abcd", 0);
    printReverse("abcd", 3);
}

print() is passed the integer 0 as a starting value and printReverse() is passed the length of the string - 1, which is the index of the last letter.

Upvotes: 1

Related Questions