user2029709 user2029709 - 4 months ago 12
Java Question

how to make reverse the recursion after recursion in Java

The goal is to print out half of the length of the previous line until it reaches 0 and then reverse it. For example, if the original size input is 5, the result is:

*****
**
*

*
**
*****


So I wrote a program like

void print(int size) {

if(size==1){
System.out.print("*");
System.out.println();
}


if(size>1){
for (int i = 0; i < size; i++) {
System.out.print("*");
}
System.out.println();
size=(int)(size/2);
print(size);
}
}


The result comes out with

*****
**
*


What is the best way to use recursion to reverse the result(the second part)?

Thanks

Answer

You implement printing only on one way. When your code achieve end of stack nothing happens. Read more about how recursive actually work, and what happend when your call methods recursive.

est way(based on your code) to achieve your goal is:

static void print(int size) {
    if (size == 0) {
        System.out.println();
    } else {
        for (int i = 0; i < size; i++) {
            System.out.print("*");
        }
        System.out.println();

        print(size / 2);

        //when stack ends point of execution will go to next statement
        //(stack ends when size==0, after that will be performed  size==1, and size=2, size== 5, eop)
        for (int i = 0; i < size; i++) {
            System.out.print("*");
        }
        System.out.println();
    }
}
Comments