3

I have an assignment to use a recursive method to print out multiple lines, each line having 3 more spaces in front of it than the previous. Here is a picture of the desired output (https://i.sstatic.net/kKz9z.png).

This is the code I have so far:

public class Prog6d {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int input = scan.nextInt();
        System.out.println(printFactorial(input));
    }

    //Calculates the factorial
    public static int printFactorial(int input) {
        if (input == 1) {
            return 1;
        }
        System.out.println("factorial(" + input + ")");
        System.out.print("   ");
        return input*printFactorial(input-1);
    }
}

I know how to make the spaces appear correctly using a for-loop, but I have no idea how to do this with recursion.

1 Answer 1

4

I do this often. I have two basic methods, related:

  1. Make a global string variable indent, initialized to the empty string. On entry to the function, lengthen it by three spaces. When you leave, shorten it to the previous length.
  2. Add a parameter indent. The initial call is with an empty string; each recursion concatenates three spaces to the value.

In each case, I just use indent as the first thing printed on the line.

Does that solve your problem?

Sign up to request clarification or add additional context in comments.

1 Comment

I would recommend approach number two over approach number one, because you’ll save yourself a lot of headache debugging your programs if you avoid global variables. If you make your calls tail-recursive, the parameterized version should be equally efficient.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.