<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Shashwat Gupta</title>
    <description>The latest articles on Forem by Shashwat Gupta (@shashwat_g27).</description>
    <link>https://forem.com/shashwat_g27</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F899291%2F99fb5c64-5eb1-4dd1-a717-50422884922f.jpg</url>
      <title>Forem: Shashwat Gupta</title>
      <link>https://forem.com/shashwat_g27</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/shashwat_g27"/>
    <language>en</language>
    <item>
      <title>"Tail Recursion" -  The most unexplored topic.</title>
      <dc:creator>Shashwat Gupta</dc:creator>
      <pubDate>Thu, 28 Jul 2022 07:20:00 +0000</pubDate>
      <link>https://forem.com/shashwat_g27/tail-recursion-the-most-unexplored-topic-198i</link>
      <guid>https://forem.com/shashwat_g27/tail-recursion-the-most-unexplored-topic-198i</guid>
      <description>&lt;p&gt;Before we get into the core, let's revise some basics.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Recursion&lt;/strong&gt; : It is a process in which a function repeatedly calls itself until a base condition is not reached or a desired result is not achieved.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Base Condition&lt;/strong&gt; : It is a condition when the function stops making recursive calls and starts returning the result. And if this condition is not defined, the program might get into infinite loop which will cause Stack Overflow Error as the stack memory will get wasted.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Stack Overflow Error&lt;/strong&gt; : To have a better understanding about what this is refer to my article on How Functions Work Internally so that you can learn about program stack, stack frame and everything else. &lt;br&gt;
So, this error basically happens when the stack memory gets exhausted due to a large amount of incoming stack frames which can't be accommodated in the stack anymore.&lt;/p&gt;

&lt;p&gt;So now let's get to the topic.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is Tail Recursion&lt;/strong&gt;?&lt;/p&gt;

&lt;p&gt;A recursive function is tail recursive when a recursive call is the last thing executed by the function.&lt;br&gt;
I know it didn't explained much about the topic. So let's see first what non-tail recursion is i.e. the traditional recursion that we all use mostly.&lt;br&gt;
 &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;In traditional / non-tail recursion, the typical model is that you perform your recursive calls first, the you take the return value of the recursive calls and calculate the result. In this manner, you don't get the result of your calculation until you have returned from every recursive call. For ex:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;main_function() {

    //Calculating the sum of N natural numbers

    int sum = nsum(5);
    display sum;
}

int nsum(int x) {

    if (x == 0) {    //base condition
        return 0;
    }
    else {
        return (x + nsum(x - 1));
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For the above pseudocode, the control flow will be like :&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s---EPLeFfY--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hwaqwic1rtdhx3scfu5u.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s---EPLeFfY--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hwaqwic1rtdhx3scfu5u.png" alt="Control Flow of Non-Tail / Traditional Recursion" width="880" height="369"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It can be said that for the result to be computed, each and every recursive call has to finish it's operation first.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Now, in tail recursion, you perform your calculations first, and then you execute the recursive call passing the result of your current step to the next step. So, the return value of any given recursive step is same as the return value of the next recursive call. Let's visualize it through the pseudocode and it's control flow.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;main_function() {

    //Calculating the sum of N natural numbers

    int sum = nsum(0, 5);
    display sum;
}

int nsum(int sum, int x) {

    if (x == 0) {    //base condition
        return sum;
    }
    else {
        return nsum(sum + x, x - 1);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The control flow goes like: &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--2ANstpzV--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zbqy0xi28ymtba5djqol.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--2ANstpzV--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zbqy0xi28ymtba5djqol.png" alt="Control Flow for Tail Recursion" width="772" height="298"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The consequence of tail recursion is that once the program is ready to perform the next recursive step, it doesn't need the current stack frame in the program stack anymore. This allows for some &lt;em&gt;optimization&lt;/em&gt; as it can be seen from image (2) and (4) that the computation process of Tail Recursion takes much lesser time than the time taken by Non-Tail Recursion. With the tail recursive function, &lt;em&gt;Stack Overflow Error&lt;/em&gt; might not be encountered.&lt;/p&gt;

&lt;p&gt;That is all about Tail Recursion that you needed to know.&lt;/p&gt;

&lt;p&gt;If you found the article interesting, please let me know in the comment section or if you have any doubts regarding it, please drop it in the same, I'll try to resolve it ASAP.&lt;/p&gt;

&lt;p&gt;Thanks for reading ❤️&lt;/p&gt;

</description>
      <category>programming</category>
      <category>recursion</category>
      <category>functional</category>
    </item>
    <item>
      <title>This is how functions work internally...</title>
      <dc:creator>Shashwat Gupta</dc:creator>
      <pubDate>Thu, 28 Jul 2022 04:14:14 +0000</pubDate>
      <link>https://forem.com/shashwat_g27/this-is-how-functions-work-internally-h10</link>
      <guid>https://forem.com/shashwat_g27/this-is-how-functions-work-internally-h10</guid>
      <description>&lt;p&gt;Hey folks, it’s mesmerizing how functions work internally, what happens in memory, how the calling mechanism works and much more….&lt;/p&gt;

&lt;p&gt;So, before knowing what happens, we should know about :&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;a. Program Stack&lt;/strong&gt;: A stack is a special area in memory which is used to store data temporarily. For functions, it holds all the function calls with bottom element as the main function because it’s the first function in a program that is executed and goes to the bottom of the stack.&lt;/p&gt;

&lt;p&gt;It works on LIFO (first-in-last-out) principle i.e. what goes in first comes out last.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;b. Stack Frame&lt;/strong&gt; : It is a buffer memory which is an element of program stack and it has the data of the called function i.e. Return Address, Input Parameter, Local Variables, Register Savings.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;c. Stack Pointer&lt;/strong&gt;: It is the pointer which points to the stack frame in the program stack i.e. the most recent function called.&lt;/p&gt;

&lt;p&gt;These three elements can be visualized as :&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--NiqnSrYG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c7q8ssep6m59lp6bchb0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--NiqnSrYG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c7q8ssep6m59lp6bchb0.png" alt="Visaulization" width="880" height="381"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, let’s get to the interesting part :&lt;/p&gt;

&lt;p&gt;Whenever a function is called, a new stack frame of the function is created with all the functions data in it.&lt;br&gt;
The stack frame is pushed into the program stack.&lt;br&gt;
The stack pointer that always points to the top of the stack points to the stack frame pushed recently.&lt;br&gt;
When the function who’s stack frame is at the top finishes execution, it’s stack frame is popped (deleted) of the stack i.e. the functions data is deleted.&lt;br&gt;
Now the control passes back to the function caller from where it was called or it can be said that the control goes to the stack frame which is now at the top after the frame that was above it got popped off.&lt;br&gt;
The above process can be explained via the pseudo-code :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;main_function() {

    func1();
}

func1() {

    func2();
}

func2() {

    // does some operation and returns
       back the results to func1()
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--zuiGq1BN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/os573q8z21rb04b7mebs.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--zuiGq1BN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/os573q8z21rb04b7mebs.png" alt="The working" width="880" height="259"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As we know, &lt;em&gt;main_function&lt;/em&gt; is always executes first in a program and according to the pseudocode above, (see in fig. a) it called &lt;em&gt;func1()&lt;/em&gt; and as it was called, it’s stack frame was generated with all it’s data and was &lt;em&gt;pushed&lt;/em&gt; (inserted) in the program stack with the stack pointer pointing to it as it is the frame pushed recently. When &lt;em&gt;func1()&lt;/em&gt; started executing, (see in fig. b) it called &lt;em&gt;func2()&lt;/em&gt; and similarly it’s stack frame also got &lt;em&gt;pushed&lt;/em&gt; into the stack and the pointer points to it. When &lt;em&gt;func2()&lt;/em&gt; finishes it’s execution, it’s stack frame consisting all it’s data got &lt;em&gt;popped&lt;/em&gt; (deleted) off the stack (see in fig. c) and the stack pointer started pointing to &lt;em&gt;func1()&lt;/em&gt; which is the function that called &lt;em&gt;func2()&lt;/em&gt; and also it’s stack frame is at the top. And when each function’s execution will get over, their frames will be &lt;em&gt;popped&lt;/em&gt; and the stack will be emptied.&lt;/p&gt;

&lt;p&gt;Hope you understood….&lt;/p&gt;

&lt;p&gt;Thanks for reading❤️&lt;/p&gt;

</description>
      <category>functional</category>
      <category>beginners</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
