I am always confused when I write a recursion program even a small one.
#include <iostream>
using namespace std;
int recursion(int x)
{
if(x == 0)
return 0;
return (x + recursion(x-1)); //recursive function call should always be in the return statement?
}
int main()
{
cout<<"SUM:"<<recursion(9);
}
Is there any another way by which recursive function call does not be in the return statement
There is no language rule saying that the recursive call has to appear as part of the
returnstatement. It can appear anywhere in the method (perhaps even in several places).For example:
That said, making the recursive call right at the very end of the function has its benefits: this is called “tail recursion” and a good compiler might be able to optimize tail recursion away.
Finally, it’s worth mentioning that in your particular example (summing the numbers from
0ton) the recursion is completely unnecessary.