Understanding working of Recursion.
Recently I was learning how to solve pattern questions using the recursion from Kunal Kushwaha . I came across a question in his lecture which was not so difficult to understand and code. I completed the whole lecture first and then coded the same on IDE. It ran successfully and I was happy, but the problem was that I was not able to understand the internal working of the code.
Actually, this was the code:
public class Erect_triangle {
public static void main(String[] args) {
patt(2,0);
}
// kunals code
private static void patt(int r, int c) {
if (r==0)
return;//when the compiler came on this line what happened next was out of my understanding.
if(r>c){
patt(r,c+1);
System.out.print("*");
}
else {
patt(r-1, 0);
System.out.println();
}
}
While debugging it I was unable to figure out how the stack memory which is created during running a recursion program was emptying itself. And how the output was being printed. It is also a fact that I did not face the same problem with other questions which he taught in his lecture, I easily understood the other questions.
Coming back to this question, I tried many times to debug it and understand it but always got confused. Then I decided to consult with my AIML professor, he advised me to not go so deep into the working of the program just to learn and understand the code.
After consulting him I decided to one last time debug the code myself again only the difference would be that I would write each step on pen and paper. I did it and then I figured out how it was working. I did and I would say I understood the working in one go and this overjoyed me so much that I exclaimed in happiness.
One thing which I learned from this small experience is that to understand recursion deeply one has to write his initial code and run them on pen and paper. Doing it with the first few questions of recursion helps us to build a good base for our future recursion programs.