I know a little bit about recursion ,but I don;t understand the return statement in which function is calling again and again, could any body help me please to understand this?
-
Tried any coding yet? – Ed Heal Feb 16 '14 at 06:15
-
This is probably a question you could get answers to on a recursion tutorial. You say you understand a little about recursion, yet you don't understand the most basic principle of it. Try looking at [this tutorial](http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=recursionPt1) which I found with a simple google search. – takendarkk Feb 16 '14 at 06:30
-
relevant: http://stackoverflow.com/questions/717725/understanding-recursion/ – AliciaBytes Feb 16 '14 at 06:39
3 Answers
This is an example of recursion where a function is calling again and again in C++.
int foo() { //1.
return foo(); //2.
}
Let's go over an explanation of the code (the comments match up with the numbers).
- Control arrives at
foo()
. foo()
has started, and it arrives at the linereturn foo();
. Whoops, looks like it is time to runfoo()
again!- Go back to line 1. Repeat until the computer runs out of battery, memory, etc.

- 7,888
- 6
- 32
- 52
The return statement in recursion has different use.
- To get termination condition or stop recursion from infinite call.
- Return some data which is used by calling step before current call.
Example:
int recursion_demo(int x)
{
// Termination condition
if(x <= 0)
return 0;
print x;
//This statement return sum of 1 to x
return x + recursion_demo(x-1);
}
Suppose we call this function as recursion_demo(5). It will print numbers from 5 to 1. Now if we will not have termination condition this recursion will keep running. The last line is recursively calculation sum of numbers from 1 to 5. so it will finally return 15. Internally function call will be in this order:
recursion_demo(5);
5 + recursion_demo(4);
4 + recursion_demo(3);
3 + recursion_demo(2);
2 + recursion_demo(1);
1 + recursion_demo(0);
recursion_demo(0) will terminate this call and their will be no further recursive call. Now it will start roll back. recursion_demo(0) has return 0 so
1 + recursion_demo(0) will be 1 + 0; = 1;
1 will return to 2 + recursion_demo(1); and this will become 2 + 1 and so on and finally recursion_demo(5)
will return 5+4+3+2+1 = 15
.

- 2,199
- 2
- 22
- 43
Recursion contains an if statement ... a base case and a recursive case. for e.g
int num(int x)
{
if (x==0)
return 0;
else
return num(x-1);
}
here the num function is once again called in the num function but with a decremented value. The output will be 5,4,3,2,1,0 for x = 5; here the "0" is the base case where the function stops ..