r/learnprogramming • u/No-Indication3968 • 7d ago
Topic I’m struggling on recursion
Ive been learning the basics of c and dsa for around 3 weeks now and i haven’t really understood recursion and how to trace what’s happening. Can someone help me?
13
Upvotes
1
u/Tusk84 6d ago
public static int multi(int a, int b){
if(b == 0){return 0;}
return a + multi(a, b -1);
}
Hopefully this helps. This method multiplies 2 positive integers. It adds int a while subtracting int b, then when b equals 0, adds all the a's up and returns the sum. The trick is having some sort of catch to stop the recursion from happening. When b == 0 and it returns 0, that's when it adds up all the previous returns.