Skip to content

Instantly share code, notes, and snippets.

@ox
Created October 18, 2011 19:03
Show Gist options
  • Save ox/1296359 to your computer and use it in GitHub Desktop.
Save ox/1296359 to your computer and use it in GitHub Desktop.
How recursion works

Recursion

Recursion is really easy to understand. It is essentially a function calling itself. Just imagine writing a function that calculates the factorial of a number n (n!). Lets see how it would expand for 4!. Remember that 1! = 1.

(factorial 4)
(4 * (factorial 3))
(4 * (3 * (factorial 3)))
(4 * (3 * (2 * (factorial 1))))
(4 * (3 * (2 * 1)))
(4 * (3 * 2))
(4 * 6)
(24)

The factorial keeps multiplying the current number by the factorial of the natural number one less than it (4 * 3!) until it reaches its terminating condition (1! = 1) which then allows all the functions before it to evaluate the return statement (n * factorial(n-1)) and pass it back up the stack.

Translated to Java code:

int factorial(int n)
	if(n == 1)
		return 1;
	else
		return n * factorial(n-1);

A recursive function takes an input and determines if it should stop (here, if n == 1) or perform an operation (here, multiplying n by something) and passing the remainder of the argument (here, all of the numbers less than n, and >= 1) to itself to do it all over again until it stops.

Every time you call a function, the computer goes off to evaluate that function for the arguments you passed in and then when that is done, it returns back to the original function call and returns a value. So when you call return n * factorial(n-1) the computer stops here to go evaluate factorial(n-1) and so on and so on until something different comes back (1) which then allows all of the stopped processes to return a value.

@vikasacharya16
Copy link

vikasacharya16 commented Jan 28, 2020

hey hey this is so funny ...! ok, what if i want to calculate an equation by using recursion as it contains special characters. SPECIAL CHARACTERS think of it ItIsPurelyAsTrIng So it has some ascii value and the recursion stops only when 1 has reached. i don't know what i'm asking.

@ox
Copy link
Author

ox commented Jan 28, 2020

Are you asking how to recursively look through a list of characters and stop when you find one you are searching for? Try making a function that takes a character to look for and the current string. Think about the terminating conditions and how you can recurse when you don't reach a terminating condition.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment