Home > Software engineering >  How to make increasing indentations in each line before some text using recursion in java?
How to make increasing indentations in each line before some text using recursion in java?

Time:10-26

I'm new to recursive methods. I am trying to create a simple JAVA program that creates a number of steps using this symbol |_ depending on the input. each recursion is supposed to print |_ then proceed to the next line and print |_ slightly further than the previous one creating a stair-like structure.

 public static void main(String[] args) {

        makeStairs(4); // invoking the method

    }

    private static void makeStairs(int steps) {

        int numstp = 0;
        if (steps > 0) {

            if (numstp != steps) {
                makeStairs(steps - 1);
                System.out.printf("|_\n");

            }
        }

    }

the output that I'm looking for:

|_
  |_
    |_
      |_

the output I have:

|_
|_   
|_
|_

Help would be highly appreciated.

CodePudding user response:

You are just trying to call make steps recursively, but within each recursion, you need to print whitespace, and since you are printing while you are exiting the recursion, you may want to do some math to determine the number of blanks to print. Looks like a homework problem so wont give the full solution here.

CodePudding user response:

You can solve this easily by printing some blank spaces immediately before printing the step itself |_

The number of spaces will be equal to the value steps

Keep in mind that each space is actually 2 spaces

So, you can use a for loop as follows

for (int i = 1; i < steps; i  ){
    System.out.print("  ");
}

Place this between makeStairs(steps - 1); and your printf statement

Output

|_
  |_
    |_
      |_
  • Related