Nested indentation with recursive method

I have an assignment to use the recursive method to print multiple lines, each line has 3 more spaces before it than the previous one. Here is a picture of the desired output ( http://i.imgur.com/mek2QMz.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 whitespace correct using a for-loop, but I have no idea how to do it with recursion.

+3


source to share


1 answer


I do this a lot. I have two main methods:

  • Indent a global string variable initialized with an empty string. When entering a function, lengthen it by three spaces. When you leave, cut it back to its previous length.
  • Add an indent parameter . The initial call is with an empty line; each recursion concatenates three spaces into a value.


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

Does your problem solve?

+2


source







All Articles