Whenever you call a function inside the body of the same function, it is called recursion. This technique can be utilized instead of looping statements to find the sum of first n numbers. In this post, I will show you how to implement this. I will be using C++ syntax, but you may take the logic and change the syntax to suit any programming language. In some programming languages, you might get a stack overflow error if you use too much recursion.
Code
The above function is a recursive function, that is it has a function call to itself in its body. The code is self explanatory and the logic is simple. Try to review the process by taking an example and going through the process one by one.
Code
function sum(n)
{
if(n==1)
return n;
else
return (n + sum(n-1));
}
cout<<sum(10);
The above function is a recursive function, that is it has a function call to itself in its body. The code is self explanatory and the logic is simple. Try to review the process by taking an example and going through the process one by one.
No comments:
Post a Comment