+ 7
What is the requirement for a recursive method?
Without it, you're gonna get infinite loop!
6 Answers
+ 7
Below are the things you need to know in order to achieve recursive algorithm.
1. Recursive Formula
2. Termination Condition
Below is the example of recursion usage to get the sum of the numbers.
int sum(int n)
{
if(n==0)
return n;
else
return n + sum(n-1);
}
Here the recursive formula is:
sum = n + sum(n-1)
The termination condition is:
n==0
+ 4
it does not require any special method to implement recursion
+ 3
the function should call the function itself in its body and the consecutive functions should be getting decreasing arguments until it reaches a terminating condition...
+ 2
u need a if/else for example,
a cod for factorial:
static long fac (long n) {
if(n>1) return (n*fak(n-1));
else return 1;
}
i hope, i can help you :)
+ 2
the requirements are a base case, and code that guarantees that you get to the base case
+ 2
first you need to define a function ,then use a base case , then return the function.
for example
def factorial(n):
if n==1:
return n
else:
return n*factorial(n-1)
the base case is if n==1 , means the simplest case .
in fact , if you want to understand programming more you can visit edx.org and take the course introduction to cs and programming using python , which is a free course taught also in the mit university.