<?xml version="1.0" encoding="UTF-8"?> <rss
version="2.0"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:wfw="http://wellformedweb.org/CommentAPI/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
><channel><title>Talk Binary &#187; c++ recursion</title> <atom:link href="http://talkbinary.com/tag/c-recursion/feed/" rel="self" type="application/rss+xml" /><link>http://talkbinary.com</link> <description>Programming Resources, Technology, Computers</description> <lastBuildDate>Fri, 30 Jul 2010 18:22:57 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.0.1</generator> <item><title>C++ Recursion</title><link>http://talkbinary.com/programming/c/c-recursion/</link> <comments>http://talkbinary.com/programming/c/c-recursion/#comments</comments> <pubDate>Tue, 20 Jul 2010 16:54:41 +0000</pubDate> <dc:creator>Diego</dc:creator> <category><![CDATA[C++]]></category> <category><![CDATA[activation records]]></category> <category><![CDATA[Base Cases]]></category> <category><![CDATA[c++ recursion]]></category> <category><![CDATA[Infinite Recursion]]></category> <category><![CDATA[recursion]]></category> <category><![CDATA[recursive function]]></category> <category><![CDATA[Runtime stack]]></category><guid
isPermaLink="false">http://talkbinary.com/?p=2813</guid> <description><![CDATA[Recursion in C++ is a function with a set of rules designed to reduce a problem into a smaller one called a base case. This may be referred to as the divide and conquer method since the idea is to solve a complex problem by solving the smaller instances of it. A classic example is [...]]]></description> <content:encoded><![CDATA[<p>Recursion in C++ is a function with a set of rules designed to reduce a problem into a smaller one called a base case. This may be referred to as the <em>divide and conquer</em> method since the idea is to solve a complex problem by solving the smaller instances of it. A classic example is the factorial function, which we&#8217;ll discuss later.</p><h3>Recursive function that displays numbers</h3><p>For our first example, let&#8217;s create a recursive function that displays a number. In order to do this, we create a function that prints a number to output, then we call itself.</p><div
class="wp_syntax"><table><tr><td
class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td
class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">void</span> printnum<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> n<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
     <span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> n <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot; &quot;</span><span style="color: #008080;">;</span>
     printnum<span style="color: #008000;">&#40;</span>n<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> <span style="color: #666666;">// Recursive call</span>
     <span style="color: #0000ff;">return</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div><p>Unfortunately, the previous example displays behavior known as <em>infinite recursion</em> on any call. Depending on the environment you are programming in, you might receive a <strong>segmentation fault</strong>. This happens because each <em>activation record</em> of a function is pushed onto the run-time stack. When you have a function that runs indefinitely, you are bound to run out of space.<br
/> <span
id="more-2813"></span><br
/><center><div
id="attachment_2822" class="wp-caption aligncenter" style="width: 144px"><a
href="http://talkbinary.com/wp-content/uploads/2010/07/RecursionInfinite.jpg"><img
src="http://talkbinary.com/wp-content/uploads/2010/07/RecursionInfinite-134x300.jpg" alt="" title="RecursionInfinite" width="134" height="300" class="size-medium wp-image-2822" /></a><p
class="wp-caption-text">Example of Infinite Recursion</p></div></center></p><h3>Base Cases in Recursion</h3><p>In order to eliminate <em>infinite recursion</em> we introduce a <em>base case</em>. A <strong>base case</strong> is a condition that determines when to terminate a recursive function. For our previous example, we&#8217;ll introduce the following base case and also make sure we are reducing our input into a smaller case each call (otherwise, we&#8217;d never reach our base case).</p><div
class="wp_syntax"><table><tr><td
class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td
class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">void</span> printnum<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> n<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
     <span style="color: #666666;">// Base case</span>
     <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span> n <span style="color: #000080;">==</span> <span style="color: #0000dd;">0</span> <span style="color: #008000;">&#41;</span> 
          <span style="color: #0000ff;">return</span><span style="color: #008080;">;</span>
     <span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> n <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot; &quot;</span><span style="color: #008080;">;</span>
&nbsp;
     <span style="color: #666666;">// Recursive call that reduces input into a smaller case</span>
     printnum<span style="color: #008000;">&#40;</span>n<span style="color: #000040;">-</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> 
     <span style="color: #0000ff;">return</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div><p>Below is an example of the output of executing such a function.</p><div
class="wp_syntax"><table><tr><td
class="line_numbers"><pre>1
</pre></td><td
class="code"><pre class="cpp" style="font-family:monospace;">printnum<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">5</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></pre></td></tr></table></div><div
class="wp_syntax"><div
class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000dd;">5</span> <span style="color: #0000dd;">4</span> <span style="color: #0000dd;">3</span> <span style="color: #0000dd;">2</span> <span style="color: #0000dd;">1</span></pre></div></div><p><center><div
id="attachment_2823" class="wp-caption aligncenter" style="width: 301px"><a
href="http://talkbinary.com/wp-content/uploads/2010/07/RecursionPrintNum.jpg"><img
src="http://talkbinary.com/wp-content/uploads/2010/07/RecursionPrintNum-291x300.jpg" alt="" title="RecursionPrintNum" width="291" height="300" class="size-medium wp-image-2823" /></a><p
class="wp-caption-text">Example of printnum(3) and output to the console</p></div></center></p><p>Now, what happens if we execute <em>printnum(-2)</em>? We will never reach our base case and thus receive <em>infinite recursion</em>. In order to avoid this behavior, its essential that we create robust base cases that allow our recursive functions to terminate.</p><p>The following is the modified version of our recursive function.</p><div
class="wp_syntax"><table><tr><td
class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td
class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">void</span> printnum<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> n<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
     <span style="color: #666666;">// Improved base case </span>
     <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span> n <span style="color: #000080;">&lt;=</span> <span style="color: #0000dd;">0</span> <span style="color: #008000;">&#41;</span> 
          <span style="color: #0000ff;">return</span><span style="color: #008080;">;</span>
     <span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> n <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot; &quot;</span><span style="color: #008080;">;</span>
&nbsp;
     <span style="color: #666666;">// Recursive call that reduces input into a smaller case</span>
     printnum<span style="color: #008000;">&#40;</span>n<span style="color: #000040;">-</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
     <span style="color: #0000ff;">return</span><span style="color: #008080;">;</span> 
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div><h3>Things to remember about C++ Recursion</h3><p>Below are some things that you should take into consideration when solving recursive problems in C++.</p><blockquote><ul><li>Recursion in C++ is a very difficult subject. It takes dedication in order to understand and master the subject.</li><li>The best way to solve recursive functions is to write down the problem on a piece of paper and identify how you are going to break down the problem into a smaller instance and when to terminate (base cases).</li><li>A good way to visualize recursion is to draw the <em>activation records</em> by drawing the run time stack of a simple recursive call</li></ul></blockquote><h3>Going further with C++ Recursion</h3><p>Now that you know the basic concept, the best way to learn recursion is by solving problems.</p><p>Next: <a
href="http://talkbinary.com/programming/c/recursion-examples/">C++ Recursion Examples</a></p><h3  class="related_post_title">Related Posts</h3><ul
class="related_post"><li><a
href="http://talkbinary.com/programming/c/c-recursion-palindrome/" title="C++ Recursion &#8211; Palindrome">C++ Recursion &#8211; Palindrome</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-tail-recursion/" title="Tail Recursion">Tail Recursion</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/introduction-to-recursion-in-c/" title="Introduction to Recursion in C++">Introduction to Recursion in C++</a> (6)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-logarithm/" title="C++ Recursion &#8211; Logarithm">C++ Recursion &#8211; Logarithm</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-greatest-common-divisor/" title="C++ Recursion &#8211; Greatest Common Divisor ">C++ Recursion &#8211; Greatest Common Divisor </a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-power-continued/" title="C++ Recursion &#8211; Power Continued">C++ Recursion &#8211; Power Continued</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-power/" title="C++ Recursion &#8211; Power">C++ Recursion &#8211; Power</a> (1)</li><li><a
href="http://talkbinary.com/programming/c/recursion-examples/" title="C++ Recursion Examples">C++ Recursion Examples</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-binary-search/" title="C++ Recursion &#8211; Binary Search">C++ Recursion &#8211; Binary Search</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-reverse-elements-of-a-vector/" title="C++ Recursion &#8211; Reverse elements of a vector">C++ Recursion &#8211; Reverse elements of a vector</a> (0)</li></ul>]]></content:encoded> <wfw:commentRss>http://talkbinary.com/programming/c/c-recursion/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>C++ Recursion &#8211; Binary Search</title><link>http://talkbinary.com/programming/c/c-recursion-binary-search/</link> <comments>http://talkbinary.com/programming/c/c-recursion-binary-search/#comments</comments> <pubDate>Thu, 25 Mar 2010 03:42:14 +0000</pubDate> <dc:creator>Diego</dc:creator> <category><![CDATA[C++]]></category> <category><![CDATA[binary search]]></category> <category><![CDATA[c++ recursion]]></category> <category><![CDATA[recursive function]]></category> <category><![CDATA[searching recursively]]></category> <category><![CDATA[sorted]]></category> <category><![CDATA[vector]]></category><guid
isPermaLink="false">http://talkbinary.com/?p=2433</guid> <description><![CDATA[Binary Search using recursion Binary search is a method to search through a sorted container in order to find a particular value. Remember that &#8220;Guess the number&#8221; game? Let&#8217;s look at the following scenario by applying the Binary Search Algorithm in order for you to understand how Binary Search works. The Guessing Game Pick a [...]]]></description> <content:encoded><![CDATA[<h2>Binary Search using recursion</h2><p>Binary search is a method to search through a <strong>sorted</strong> container in order to find a particular value.</p><p>Remember that &#8220;Guess the number&#8221; game? Let&#8217;s look at the following scenario by applying the Binary Search Algorithm in order for you to understand how Binary Search works.</p><blockquote><h3>The Guessing Game</h3><p>Pick a number from 0 &#8211; 100 and depending on your guess, I&#8217;ll either say Correct, Higher, or Lower. What would you choose?</p><table><tr><td>0</td><td>1</td><td>&#8230;</td><td>49</td><td>50</td><td>51</td><td>&#8230;</td><td>99</td><td>100</td></tr></table><p>Well, 50 of course! Why? Best case you get it correct. Worst case you&#8217;ll either get a &#8220;Higher&#8221; or &#8220;Lower&#8221;. Now think about the following, if you got &#8220;Higher&#8221; you eliminated 0-49, or 51-100 if &#8220;Lower&#8221;, in other words, you eliminate HALF the possibilities.</p><table><tr><td>50</td><td>51</td><td>&#8230;</td><td>74</td><td>75</td><td>76</td><td>&#8230;</td><td>99</td><td>100</td></tr></table><p>Well, let&#8217;s say it was &#8220;Higher&#8221;. What would you guess after? 75. Since it&#8217;s in between 50 &#8211; 100. If you didn&#8217;t guess correctly, you&#8217;ll be facing the similar scenario as before. You&#8217;ll end up eliminating half the possibilities!</p></blockquote><h2>Getting started on the Binary Search Algorithm</h2><p>Let&#8217;s break up the rules for the Binary Search Algorithm.</p><ul><li>If the number guessed is correct, return the location of the element</li><li>If the number is at a &#8220;Higher&#8221; location, eliminate the lower half, else eliminate the upper half</li></ul><p><br/>Given this information, what would we need for our function header?<br
/> <span
id="more-2433"></span></p><blockquote><h3>Header for Binary Search</h3><p>We&#8217;d need the container and values indicating where our lower and higher boundary are. We&#8217;ll be returning the location of the value, else -1 if not found. We&#8217;ll also need the key we are looking for.</p><pre lang="c++">int binarySearch(vector <int> vec, int low, int high, int key) {</pre></blockquote><p>Next, what would our base cases be? When the element we &#8220;pick&#8221; is correct, or we exhausted searching through our container.</p><blockquote><h3>Base Case for Binary Search</h3><p>Like mentioned before, the first element to be compared to in our container would be the middle element. We&#8217;d also check to see if we exhausted our search by the following base case.</p><pre lang="c++">int binarySearch(vector <int> vec, int low, int high, int key) {

    // We exhausted our search
    if ( low > high ) {
         return -1;
    } 

    // The middle element
    int mid = (low + high)/2;

    if ( vec[mid] == key ) {
        return mid;
    }
</pre><p><br/>If you don&#8217;t understand why we have our initial base case, follow along. You&#8217;ll understand shortly.</p></blockquote><p>Next, how would we break down our Binary Search on the next recursive call? Well, by simply assigning a new low, or high depending if they key was higher or lower than the one compared to.</p><h2>Binary Search using Recursion</h2><pre lang="c++">int binarySearch(vector <int> vec, int low, int high, int key) {

    // We exhausted our search
    if ( low > high ) {
         return -1;
    } 

    // The middle element
    int mid = (low + high)/2;

    if ( vec[mid] == key ) {
        return mid;
    }

    //If middle index value is larger than our key,
    //we search the lower half of the vector
    //else we search the upper half

    else if ( vec[mid] > key ) {
         return binarySearch(vec, low, mid-1, key);
    } else {
         return binarySearch(vec, mid+1, high, key);
    }
}</pre><p><br/>If you didn&#8217;t understand our initial base case, run through this algorithm using our recursive calls on a small vector without the key you are looking for and you&#8217;ll realize why our base case works as follows.</p><h2>Going further</h2><ol><li>Can you make a <a
href="http://talkbinary.com/programming/c/c-helper-functions/">helper function</a> to make this calling this function cleaner for the user?</li></ul><li>Would this algorithm work using an unsorted array?</li></ol><h3  class="related_post_title">Related Posts</h3><ul
class="related_post"><li><a
href="http://talkbinary.com/programming/c/c-recursion/" title="C++ Recursion">C++ Recursion</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-logarithm/" title="C++ Recursion &#8211; Logarithm">C++ Recursion &#8211; Logarithm</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-palindrome/" title="C++ Recursion &#8211; Palindrome">C++ Recursion &#8211; Palindrome</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-reverse-elements-of-a-vector/" title="C++ Recursion &#8211; Reverse elements of a vector">C++ Recursion &#8211; Reverse elements of a vector</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-tail-recursion/" title="Tail Recursion">Tail Recursion</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-helper-functions/" title="C++ Helper Functions">C++ Helper Functions</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-greatest-common-divisor/" title="C++ Recursion &#8211; Greatest Common Divisor ">C++ Recursion &#8211; Greatest Common Divisor </a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-fibonacci/" title="C++ Recursion &#8211; Fibonacci">C++ Recursion &#8211; Fibonacci</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-printing-elements-of-a-vector/" title="C++ Recursion &#8211; Printing Elements of a Vector">C++ Recursion &#8211; Printing Elements of a Vector</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-power-continued/" title="C++ Recursion &#8211; Power Continued">C++ Recursion &#8211; Power Continued</a> (0)</li></ul>]]></content:encoded> <wfw:commentRss>http://talkbinary.com/programming/c/c-recursion-binary-search/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>C++ Recursion &#8211; Logarithm</title><link>http://talkbinary.com/programming/c/c-recursion-logarithm/</link> <comments>http://talkbinary.com/programming/c/c-recursion-logarithm/#comments</comments> <pubDate>Sun, 14 Mar 2010 08:25:08 +0000</pubDate> <dc:creator>Diego</dc:creator> <category><![CDATA[C++]]></category> <category><![CDATA[Functions]]></category> <category><![CDATA[c++ recursion]]></category> <category><![CDATA[log]]></category> <category><![CDATA[log base 2]]></category> <category><![CDATA[log base n]]></category> <category><![CDATA[log function]]></category> <category><![CDATA[log recursive function]]></category> <category><![CDATA[math]]></category> <category><![CDATA[recursive function]]></category><guid
isPermaLink="false">http://talkbinary.com/?p=2397</guid> <description><![CDATA[Finding the logarithm of a number given a base Below is an example of how to determine the logarithm of a number of base 2 and then of any base. The logarithm of a number using a given base is power to which the base must be raised to result in the number. This tutorial [...]]]></description> <content:encoded><![CDATA[<h2>Finding the logarithm of a number given a base</h2><p>Below is an example of how to determine the logarithm of a number of base 2 and then of any base. The logarithm of a number using a given base is power to which the base must be raised to result in the number. This tutorial assumes you understand <a
href="http://talkbinary.com/programming/c/introduction-to-recursion-in-c/">C++ Recursion</a> and the <a
href="http://talkbinary.com/programming/c/c-recursion-power/">C++ Recursion &#8211; Power</a> function.</p><blockquote><h3>Example of finding the logarithm given a base</h3><p>You could find the base using two different methods.</p><ol><li>Multiply the base by itself until you receive the number.</li><li>Divide the number by the base, and repeat until you result in 1. For this method the result is the number of computations to get to 1.</li></ol><p><m>logBase2(8) = 3<br
/> 2 * 2 * 2 = 8</p><p>Method 2:<br
/> 8/2 = 4<br
/> 4/2 = 2<br
/> 2/2 = 1</p><p>logBaseN(16,2) = 4<br
/> 2 * 2 * 2 * 2 = 16</p><p>Method 2:<br
/> 16/2 = 8<br
/> 8/2 = 4<br
/> 4/2 = 2<br
/> 2/2 = 1<br
/> </m><br
/> <br/></p></blockquote><h2>Recursive version of logBase2 function</h2><p>Given the example above, could you come up with a logBase2 recursive function?  Let&#8217;s try using the 2nd method described above. So what would be our base case and header?<br
/> <span
id="more-2397"></span></p><blockquote><h3>Header and base case for logBase2 function</h3><p>Below is the header for the logBase2 function. We only need one parameter.</p><pre lang="c++">int logBase2(int num) { </pre><p><br/>What about our base case? By using our second method we want to stop dividing our number by our base 2 until we result in 1.</p><pre lang="c++">int logBase2(int num) { 

      if ( num == 1 )
           return 0; </pre></blockquote><blockquote><h3>LogBase2 Recursive Function</h3><p>Looking back at our second method, we count the number of computations until our number is 1. Let&#8217;s do this. We also break down the problem by diving our number by 2 at each iteration.</p><pre lang="c++">int logBase2(int num) { 

      if ( num == 1 )
           return 0; 

      return 1 + logBase2(num/2);

}</pre><p><br/>Yes, that&#8217;s it. This recursive function will return the number which is the power to the base to get to our number.</p></blockquote><h2>Recursive version of logBaseN function</h2><p>Our previous function took care of logBase2 values. What about logBaseN values? This simply means you pass in the base as well. This addition should be trivial.</p><blockquote><h3>LogBase2 Recursive Function</h3><p>Now, we are simply modifying our previous function but this time around we are also passing in the base.</p><pre lang="c++">int logBaseN(int num, int base) { 

      if ( num == 1 )
           return 0; 

      return 1 + logBase2(num/base, base);

}</pre><p><br/></p></blockquote><h2>Going further</h2><ol><li>1. Can you take care of error detection? What if a user puts in erroneous numbers or bases?</li></ol><h3  class="related_post_title">Related Posts</h3><ul
class="related_post"><li><a
href="http://talkbinary.com/programming/c/c-recursion/" title="C++ Recursion">C++ Recursion</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-palindrome/" title="C++ Recursion &#8211; Palindrome">C++ Recursion &#8211; Palindrome</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-power-continued/" title="C++ Recursion &#8211; Power Continued">C++ Recursion &#8211; Power Continued</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-power/" title="C++ Recursion &#8211; Power">C++ Recursion &#8211; Power</a> (1)</li><li><a
href="http://talkbinary.com/programming/c/c-tail-recursion/" title="Tail Recursion">Tail Recursion</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-binary-search/" title="C++ Recursion &#8211; Binary Search">C++ Recursion &#8211; Binary Search</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-greatest-common-divisor/" title="C++ Recursion &#8211; Greatest Common Divisor ">C++ Recursion &#8211; Greatest Common Divisor </a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-helper-functions/" title="C++ Helper Functions">C++ Helper Functions</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/introduction-to-recursion-in-c/" title="Introduction to Recursion in C++">Introduction to Recursion in C++</a> (6)</li><li><a
href="http://talkbinary.com/programming/c/c-variables-and-data-types/" title="C++ Variables and Data Types">C++ Variables and Data Types</a> (0)</li></ul>]]></content:encoded> <wfw:commentRss>http://talkbinary.com/programming/c/c-recursion-logarithm/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>C++ Recursion &#8211; Palindrome</title><link>http://talkbinary.com/programming/c/c-recursion-palindrome/</link> <comments>http://talkbinary.com/programming/c/c-recursion-palindrome/#comments</comments> <pubDate>Thu, 11 Mar 2010 06:30:38 +0000</pubDate> <dc:creator>Diego</dc:creator> <category><![CDATA[C++]]></category> <category><![CDATA[Functions]]></category> <category><![CDATA[c++ function]]></category> <category><![CDATA[c++ recursion]]></category> <category><![CDATA[function]]></category> <category><![CDATA[palindrome]]></category> <category><![CDATA[recursion]]></category> <category><![CDATA[recursive function]]></category> <category><![CDATA[string]]></category> <category><![CDATA[substr]]></category> <category><![CDATA[substring]]></category><guid
isPermaLink="false">http://talkbinary.com/?p=2376</guid> <description><![CDATA[Determining if a string is a Palindrome using recursion Below is an example of how to determine if a word is a palindrome using recursion. A Palindrome is a string that could be read the same way in either direction such as racecar, mom, and even a. This tutorial expects you to understands the following. [...]]]></description> <content:encoded><![CDATA[<h2>Determining if a string is a Palindrome using recursion</h2><p>Below is an example of how to determine if a word is a palindrome using recursion. A <strong>Palindrome</strong> is a string that could be read the same way in either direction such as<em> racecar</em>,<em> mom</em>, and even <em>a</em>.  This tutorial expects you to understands the following.</p><p><a
href="http://talkbinary.com/programming/c/introduction-to-recursion-in-c/">C++ Recursion</a></p><blockquote><h3>Example of finding if a word is a palindrome</h3><p>To determine if a word is a palindrome do the following.</p><ol><li>Compare the first and last character</li><li>If these characters are the same, disregard these characters and repeat until one one character or no characters remain</li></ol><p>Example:</p><pre lang="c++">

// Check first and last character
[ r ] [ a ] [ c ] [ e ] [ c ] [ a ] [ r ] 

// Second iteration
[ a ] [ c ] [ e ] [ c ] [ a ] 

// Third iteration
[ c ] [ e ] [ c ]  

// Fourth iteration
[ e ]

// The word is a palindrome.
</pre><p><br/><br
/> Now let&#8217;s try one that isn&#8217;t a palindrome.</p><pre lang="c++">
// First iteration
[ t ] [ a ] [ b ] [ t ]

// In our second iteration, a and b don't match
[ a ] [ b ]</pre></blockquote><p><span
id="more-2376"></span></p><h2> Creating an is Palindrome function using recursion</h2><p>There are multiple ways to create a recursive function. Try coming up with your own before seeing the one below. As always, we&#8217;ll start with the function header.</p><blockquote><h3>Function header for is Palindrome</h3><p>We&#8217;ll be using the following function header.</p><pre lang="c++">bool isPalindrome(string word); </pre><p><br/>You may ask, do we need more parameters? Not necessarily. Think <strong>substr</strong>.</p></blockquote><blockquote><h3>Base Cases for is Palindrome</h3><p>If you recall we had three base cases.</p><ol><li>If the first and last character don&#8217;t match, the word is not a palindrome</li><li>If the word contains one or no characters, the word is a palindrome</li></ol><pre lang="c++">bool isPalindrome(string word) { 

      int strlen = word.size();

     // Base Case #1
     if ( word[0] != word[strlen - 1] )
         return false;

     // Base Cases #2, #3
     else if ( strlen <= 1 )
          return true;
</pre><p><br/>We store the length of the word so we don't have to be recomputing it more than once. You'll see why later.</p></blockquote><blockquote><h3>Recursive call for is Palindrome</h3><p>If you also recall from our initial example, if the first and last character match, we disregard them in our next comparison. How do we call <strong>isPalindrome</strong> with this new word? Think <strong>substr</strong>.</p><h4>Substr returns a substring of a string</h4><p><strong>substr</strong> returns a substring of a string.</p><pre lang="c++">bool isPalindrome(string word) { 

      int strlen = word.size();

     // Base Case #1
     if ( word[0] != word[strlen - 1] )
         return false;

     // Base Cases #2, #3
     else if ( strlen <= 1 )
          return true;

     // At this point we know the characters matched
     else
          return isPalindrome(word.substr(1, strlen - 2));

}
</pre><p><br/> Why do we return a substring with the following parameters? If you don't recall how substr works, simply follow the next explanation. In essence, at each recursive call we are reducing the strings in the same way shown in the explanation.</p></blockquote><h2>string::subtr</h2><p>The <strong>substr</strong> functions returns a substring with the following parameters of the current object.</p><blockquote><h3>Paramters of substr</h3><ul><li>pos - Start position of the character of the <em>current</em> word</li><li>n - Length of the substring starting from the start position <em>pos</em>.</li></ul><h4>Return value of substr</h4><p>A <strong>string</strong> containing the substring of the object.</p><h4>Example usage of substr</h4><pre lang="c++">string msg = "racecar";

cout << msg << endl;

// Our new substr should start at position 1 and be of size 5
// which is shown below.
//
// [ r ] [ a ] [ c ] [ e ] [ c ] [ a ] [ r ]
//        | S                              |
string new msg = msg.substr(1, msg.size()-2);

cout << newmsg << endl;</pre><p><br/>Will result in the following.</p><pre>racecar

aceca</pre><p><br/>This should make you understand how the recursive calls are made to determine if the word is a palindrome.</p></blockquote><h3>Going further</h3><ol><li>Can you apply this using a vector?</li></ol><h3  class="related_post_title">Related Posts</h3><ul
class="related_post"><li><a
href="http://talkbinary.com/programming/c/c-recursion/" title="C++ Recursion">C++ Recursion</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-greatest-common-divisor/" title="C++ Recursion &#8211; Greatest Common Divisor ">C++ Recursion &#8211; Greatest Common Divisor </a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-power-continued/" title="C++ Recursion &#8211; Power Continued">C++ Recursion &#8211; Power Continued</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-power/" title="C++ Recursion &#8211; Power">C++ Recursion &#8211; Power</a> (1)</li><li><a
href="http://talkbinary.com/programming/c/c-tail-recursion/" title="Tail Recursion">Tail Recursion</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-logarithm/" title="C++ Recursion &#8211; Logarithm">C++ Recursion &#8211; Logarithm</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-reverse-elements-of-a-vector/" title="C++ Recursion &#8211; Reverse elements of a vector">C++ Recursion &#8211; Reverse elements of a vector</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-fibonacci/" title="C++ Recursion &#8211; Fibonacci">C++ Recursion &#8211; Fibonacci</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-factorial/" title="C++ Recursion &#8211; Factorial">C++ Recursion &#8211; Factorial</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-summation/" title="C++ Recursion &#8211; Summation ">C++ Recursion &#8211; Summation </a> (2)</li></ul>]]></content:encoded> <wfw:commentRss>http://talkbinary.com/programming/c/c-recursion-palindrome/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>C++ Recursion &#8211; Reverse elements of a vector</title><link>http://talkbinary.com/programming/c/c-recursion-reverse-elements-of-a-vector/</link> <comments>http://talkbinary.com/programming/c/c-recursion-reverse-elements-of-a-vector/#comments</comments> <pubDate>Mon, 08 Mar 2010 22:09:48 +0000</pubDate> <dc:creator>Diego</dc:creator> <category><![CDATA[C++]]></category> <category><![CDATA[Functions]]></category> <category><![CDATA[c++ recursion]]></category> <category><![CDATA[function]]></category> <category><![CDATA[iteration]]></category> <category><![CDATA[iterative]]></category> <category><![CDATA[recursion]]></category> <category><![CDATA[recursive]]></category> <category><![CDATA[reverse]]></category> <category><![CDATA[Swapping]]></category> <category><![CDATA[vector]]></category><guid
isPermaLink="false">http://talkbinary.com/?p=2327</guid> <description><![CDATA[Reversing the elements of a vector using recursion Below is an example of how to reverse the elements of a vector using recursion. This tutorial expects you to understand the following. C++ Recursion Example of reversing the elements of a vector Below is an example of how one would reverse the elements of a vector [...]]]></description> <content:encoded><![CDATA[<h2>Reversing the elements of a vector using recursion</h2><p>Below is an example of how to reverse the elements of a vector using recursion. This tutorial expects you to understand the following.</p><p><a
href="http://talkbinary.com/programming/c/introduction-to-recursion-in-c/">C++ Recursion</a></p><blockquote><h3>Example of reversing the elements of a vector</h3><p>Below is an example of how one would reverse the elements of a vector by simply intuition.</p><pre lang="c++">
// Our vector with size 5
[ X ] [ B ] [ A ] [ N ] [ Y ]
[ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ]

//Step 1: Swap entry 0 (first) with the entry n (last)
[ Y ] [ B ] [ A ] [ N ] [ X ]
[ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] 

//Step 2: Swap entry 1 with entry 3 (n -1)
[ Y ] [ N ] [ A ] [ B ] [ X ]
[ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ]

//Step 3: No swap needed for 3rd entry (or middle entry)
[ Y ] [ N ] [ A ] [ B ] [ X ]
[ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ]
</pre><p><br/><br
/> Notice how once we arrive at the entry in the middle of the vector we don&#8217;t continue. Why? The values beyond this entry have already been swapped. Keep this in mind.</p></blockquote><h2>Reversing the elements of a vector using iteration</h2><p>Before we try making a recursive function to reverse the elements of a vector, let&#8217;s make one using iteration. By following the method described in the method above, it&#8217;s easy to see that we are simply swapping the ith and (nth &#8211; ith) variables <strong>(Example: the 0th and the 4th (4th &#8211; 0th) element)</strong>.</p><blockquote><h3>Reversing the elements of a vector using iteration</h3><p>The iterative solution for reversing the elements of a vector is below. Make sure you are trying all these functions if you haven&#8217;t before on your own.</p><pre lang="c++">
//We pass the vector by reference
void reverseElements(vector <int> &#038;vec) {

     //Temp variable for swapping
     int temp;

     int n = vec.size()-1;

     //Iterate vec.size()/2 times
     for ( int i = 0; i < vec.size()/2; i++ ) {

          // The swapping of elements
          temp = vec[i];
          vec[i] = vec[n-i];
          vec[n] = temp;

     }

     return;
}</pre><p><br/><br
/> Make sure you understand this completely before moving forward. Try working it out by hand.</p></blockquote><p><span
id="more-2327"></span></p><h2>Reversing the elements of a vector using recursion</h2><p>So how would we start? What would the function header be?</p><blockquote><h3>Function header for reversing elements of a vector</h3><p>So what would we need for our function header? We need the vector of course and also passed in by reference. Then we also need a way of knowing the two elements that are going to be swapped.</p><pre lang="c++">void revVector(vector <int> &#038;vec, int lo, int hi);

// Which would be called with the following //
vector <int> a;

// Populate a...

revVector(a, 0, a.size()-1);
</pre><p><br/><br
/> We'll name this revVector for know and the two variables to be swapped lo and hi. How are we going to use these two variables? Every new recursive calls we will increase lo and decrease hi until our base case.</p></blockquote><p>So what would be our base case?</p><blockquote><h3>Base case for reversing elements of a vector</h3><p>Your first guess might be</p><pre lang="c++">if ( lo == hi ) return; </pre><p><br/>But, what if we have an even number of entries? This wouldn't be the case. Let's refine it.</p><pre lang="c++">if ( lo >= hi ) return; </pre><p><br/>Now that would take care of when the vector is of even or odd size. Why? Try figuring it out if you haven't.</p></blockquote><p>Below is the rest of the function.</p><blockquote><h3>Solution</h3><pre lang="c++">void revVector(vector <int> &#038;vec, int lo, int hi) {

     // First base case //
     if ( lo >= hi ) return;

     // The swapping
     int temp;
     temp = vec[lo];
     vec[lo] = vec[hi];
     vec[hi] = temp;

     // Next recursive call increase lo, and decrease hi by 1
     revVector(vec, lo+1, hi-1);

     return;
}</pre></blockquote><h2>Going further</h2><ol><li>Can you make a helper function for this recursive function? [Hint: <strong><a
href="http://talkbinary.com/programming/c/c-helper-functions/">C++ Helper Functions</a>]</strong></li><li>Can you write a function that does the swap which would be called within your recursive/iterative version?</li></ol><h3  class="related_post_title">Related Posts</h3><ul
class="related_post"><li><a
href="http://talkbinary.com/programming/c/c-recursion-fibonacci/" title="C++ Recursion &#8211; Fibonacci">C++ Recursion &#8211; Fibonacci</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-power-continued/" title="C++ Recursion &#8211; Power Continued">C++ Recursion &#8211; Power Continued</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-power/" title="C++ Recursion &#8211; Power">C++ Recursion &#8211; Power</a> (1)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-palindrome/" title="C++ Recursion &#8211; Palindrome">C++ Recursion &#8211; Palindrome</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-factorial/" title="C++ Recursion &#8211; Factorial">C++ Recursion &#8211; Factorial</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-summation/" title="C++ Recursion &#8211; Summation ">C++ Recursion &#8211; Summation </a> (2)</li><li><a
href="http://talkbinary.com/programming/c/introduction-to-recursion-in-c/" title="Introduction to Recursion in C++">Introduction to Recursion in C++</a> (6)</li><li><a
href="http://talkbinary.com/programming/c/special-functions/fibonacci-in-c/" title="Fibonacci in C++">Fibonacci in C++</a> (3)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion/" title="C++ Recursion">C++ Recursion</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-binary-search/" title="C++ Recursion &#8211; Binary Search">C++ Recursion &#8211; Binary Search</a> (0)</li></ul>]]></content:encoded> <wfw:commentRss>http://talkbinary.com/programming/c/c-recursion-reverse-elements-of-a-vector/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>C++ Recursion &#8211; Fibonacci</title><link>http://talkbinary.com/programming/c/c-recursion-fibonacci/</link> <comments>http://talkbinary.com/programming/c/c-recursion-fibonacci/#comments</comments> <pubDate>Wed, 24 Feb 2010 06:41:24 +0000</pubDate> <dc:creator>Diego</dc:creator> <category><![CDATA[C++]]></category> <category><![CDATA[c++ fibonacci function]]></category> <category><![CDATA[c++ recursion]]></category> <category><![CDATA[fibonacci function]]></category> <category><![CDATA[fibonacci recursion]]></category> <category><![CDATA[fibonacci recursive]]></category> <category><![CDATA[fibonacci sequence]]></category> <category><![CDATA[function]]></category> <category><![CDATA[iteration]]></category> <category><![CDATA[iterative]]></category> <category><![CDATA[recursion]]></category> <category><![CDATA[recursive]]></category><guid
isPermaLink="false">http://talkbinary.com/?p=2249</guid> <description><![CDATA[The Fibonacci Sequence Below is an example of how to create the recursive version of the Fibonacci sequence. But first of all, what is it? * This tutorial assumes you understand the following: Introduction to Recursion in C++ Fibonacci is a well known number sequence that models the growth of a rabbit population amongst other [...]]]></description> <content:encoded><![CDATA[<h3>The Fibonacci Sequence</h3><hr
/> Below is an example of how to create the recursive version of the Fibonacci sequence. But first of all, what is it?<br
/> <br/><br
/> * This tutorial assumes you understand the following:</p><ul><li><a
href="http://talkbinary.com/programming/c/introduction-to-recursion-in-c/">Introduction to Recursion in C++</a></li></ul><blockquote><p>Fibonacci is a well known number sequence that models the growth of a rabbit population amongst other things found in nature.</p></blockquote><p>Below is the Fibonacci numbers computed up to the 11th term.</p><table
border="1" bordercolor="black"><tr
border-color="white"><td
border-color="white">0</t></p><td
border-color="white">1</td><td
border-color="white">2</td><td
border-color="white">3</td><td
bordercolor="white">4</td><td
bordercolor="white">5</td><td
bordercolor="white">6</td><td
bordercolor="white">7</td><td
bordercolor="white">8</td><td
bordercolor="white">9</td><td
bordercolor="white">10</td><td
bordercolor="white">11</td></tr><tr
bordercolor="white"><td>0</t></p><td>1</td><td>1</td><td>2</td><td>3</td><td>5</td><td>8</td><td>13</td><td>21</td><td>34</td><td>55</td><td>89</td></tr></table><h3>Iterative version of Fibonacci</h3><hr
/> Before we create the recursive version of Fibonacci, let&#8217;s look at how to create the iterative version by looking at the formula.</p><blockquote><h3>Fibonacci Formula</h3><p>Fibonacci(0) = 0;<br
/> Fibonacci(1) = 1;<br
/> Fibonacci(n) = Fibonacci(n-1) + Fibonacci(n-2);</p></blockquote><p>So how would we do an iterative version? I&#8217;ll walk you through the code.</p><div
class="wp_syntax"><table><tr><td
class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
</pre></td><td
class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #666666;">// The value of n is the Fibonacci number we want to compute //</span>
<span style="color: #0000ff;">int</span> fibonacci<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> n<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> 
&nbsp;
    <span style="color: #666666;">//Our two initial values</span>
    <span style="color: #0000ff;">int</span> fib1 <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span>
    <span style="color: #0000ff;">int</span> fib2 <span style="color: #000080;">=</span> <span style="color: #0000dd;">1</span><span style="color: #008080;">;</span> 
&nbsp;
    <span style="color: #666666;">//Our running value</span>
    <span style="color: #0000ff;">int</span> fib <span style="color: #000080;">=</span> fib1<span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #666666;">// Computing the nth value of Fibonacci //</span>
&nbsp;
   <span style="color: #0000ff;">return</span> fib<span style="color: #008080;">;</span></pre></td></tr></table></div><p><br/><br
/> So how would we compute the value of the nth value of the Fibonacci sequence? We can do it with a for loop, to add UP to the value we are looking for. In other words, if we were doing it by hand, we&#8217;d do it as following:<br
/> <span
id="more-2249"></span></p><div
class="wp_syntax"><table><tr><td
class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
</pre></td><td
class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #666666;">//Initial cases</span>
fib<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span>
fib<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">1</span><span style="color: #008080;">;</span>
&nbsp;
fib<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">2</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">=</span> fib<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span> <span style="color: #000040;">+</span> fib<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">1</span> <span style="color: #000040;">+</span> <span style="color: #0000dd;">0</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">1</span><span style="color: #008080;">;</span>
&nbsp;
fib<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">3</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">=</span> fib<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">2</span><span style="color: #008000;">&#41;</span> <span style="color: #000040;">+</span> fib<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">1</span> <span style="color: #000040;">+</span> <span style="color: #0000dd;">1</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">2</span><span style="color: #008080;">;</span>
&nbsp;
fib<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">4</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">=</span> fib<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">3</span><span style="color: #008000;">&#41;</span> <span style="color: #000040;">+</span> fib<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">2</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">2</span> <span style="color: #000040;">+</span> <span style="color: #0000dd;">1</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">3</span><span style="color: #008080;">;</span>
&nbsp;
fib<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">5</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">=</span> fib<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">4</span><span style="color: #008000;">&#41;</span> <span style="color: #000040;">+</span> fib<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">3</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">3</span> <span style="color: #000040;">+</span> <span style="color: #0000dd;">2</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">5</span><span style="color: #008080;">;</span> 
&nbsp;
fib<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">6</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">=</span> fib<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">5</span><span style="color: #008000;">&#41;</span> <span style="color: #000040;">+</span> fib<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">3</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">5</span> <span style="color: #000040;">+</span> <span style="color: #0000dd;">3</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">8</span><span style="color: #008080;">;</span>
&nbsp;
..
&nbsp;
<span style="color: #007788;">fib</span><span style="color: #008000;">&#40;</span>n<span style="color: #008000;">&#41;</span> <span style="color: #000080;">=</span> fib<span style="color: #008000;">&#40;</span>n <span style="color: #000040;">-</span> <span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span> <span style="color: #000040;">+</span> fib<span style="color: #008000;">&#40;</span>n<span style="color: #000040;">-</span><span style="color: #0000dd;">2</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></pre></td></tr></table></div><p><br/><br
/> You could think of fib(n), fib(n-1), and fib(n-2) being fib, fib1, and fib2 respectively in our code. Try coming up with a solution to compute the nth Fibonacci number.</p><p>The code to compute the Fibonacci sequence for iterative version is below.</p><div
class="wp_syntax"><table><tr><td
class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
</pre></td><td
class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #666666;">// The value of n is the Fibonacci number we want to compute //</span>
<span style="color: #0000ff;">int</span> fibonacci<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> n<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> 
&nbsp;
    <span style="color: #666666;">//Our two initial values</span>
    <span style="color: #0000ff;">int</span> fib1 <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span>
    <span style="color: #0000ff;">int</span> fib2 <span style="color: #000080;">=</span> <span style="color: #0000dd;">1</span><span style="color: #008080;">;</span> 
&nbsp;
    <span style="color: #666666;">//Our running value</span>
    <span style="color: #0000ff;">int</span> fib <span style="color: #000080;">=</span> fib1<span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #666666;">// Computing the nth value of Fibonacci //</span>
    <span style="color: #0000ff;">for</span> <span style="color: #008000;">&#40;</span> <span style="color: #0000ff;">int</span> i <span style="color: #000080;">=</span> <span style="color: #0000dd;">1</span><span style="color: #008080;">;</span> i <span style="color: #000080;">&lt;</span> n<span style="color: #008080;">;</span> i<span style="color: #000040;">++</span> <span style="color: #008000;">&#41;</span> 
    <span style="color: #008000;">&#123;</span> 
        <span style="color: #666666;">// Fib(n) = fib(n-1) + fib(n-2);</span>
        fib <span style="color: #000080;">=</span> fib1 <span style="color: #000040;">+</span> fib2<span style="color: #008080;">;</span>
&nbsp;
        <span style="color: #666666;">// The next two numbers are set this way </span>
        <span style="color: #666666;">// to be used in the next computation of fib(n) </span>
        <span style="color: #666666;">// Work it out by hand if you don't understand it.</span>
&nbsp;
        <span style="color: #666666;">// Fib(n-1) = fib(n-2)</span>
        <span style="color: #666666;">// Fib(n-2) = fib</span>
        fib1 <span style="color: #000080;">=</span> fib2<span style="color: #008080;">;</span>
&nbsp;
        fib2 <span style="color: #000080;">=</span> fib<span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
   <span style="color: #666666;">// Return result</span>
   <span style="color: #0000ff;">return</span> fib<span style="color: #008080;">;</span></pre></td></tr></table></div><p><br/></p><h3>Recursive version Fibonacci</h3><hr
/> To create the recursive version of Fibonacci, we start like always with the base cases. In case you forgot, the formula for Fibonacci is below.</p><blockquote><h3>Fibonacci Formula</h3><p>Fibonacci(0) = 0;<br
/> Fibonacci(1) = 1;<br
/> Fibonacci(n) = Fibonacci(n-1) + Fibonacci(n-2);</p></blockquote><p>So let&#8217;s start by creating the base case and function header.</p><div
class="wp_syntax"><table><tr><td
class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td
class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">int</span> fibonacci<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> n<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
&nbsp;
    <span style="color: #666666;">// Base cases</span>
    <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span> n <span style="color: #000080;">==</span> <span style="color: #0000dd;">0</span> <span style="color: #008000;">&#41;</span> <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span>
    <span style="color: #0000ff;">else</span> <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span> n <span style="color: #000080;">==</span> <span style="color: #0000dd;">1</span> <span style="color: #008000;">&#41;</span> <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">1</span><span style="color: #008080;">;</span>
&nbsp;
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div><p>That was quite simple wasn&#8217;t it? An image describing the function calls are below.</p><p><center><a
href="http://talkbinary.com/wp-content/uploads/2010/02/fib01.jpg"><img
src="http://talkbinary.com/wp-content/uploads/2010/02/fib01.jpg" alt="" title="fib01" width="259" height="135" class="aligncenter size-full wp-image-2258" /></a></center></p><p>So how do we go on by computing the nth term of the Fibonacci sequence? Try it out on your own first then come back. If you translated the formula correctly into code, it should then look like the following.</p><div
class="wp_syntax"><table><tr><td
class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td
class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">int</span> fibonacci<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> n<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
&nbsp;
    <span style="color: #666666;">// Base cases</span>
    <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span> n <span style="color: #000080;">==</span> <span style="color: #0000dd;">0</span> <span style="color: #008000;">&#41;</span> <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span>
    <span style="color: #0000ff;">else</span> <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span> n <span style="color: #000080;">==</span> <span style="color: #0000dd;">1</span> <span style="color: #008000;">&#41;</span> <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">1</span><span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #666666;">//This is returning fibonacci(n) = fibonacci(n-1) + fibonacci(n-2)</span>
    <span style="color: #0000ff;">else</span> 
         <span style="color: #0000ff;">return</span> fibonacci<span style="color: #008000;">&#40;</span>n<span style="color: #000040;">-</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span> <span style="color: #000040;">+</span> fibonacci<span style="color: #008000;">&#40;</span>n<span style="color: #000040;">-</span><span style="color: #0000dd;">2</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div><p><br/></p><h3>Explanation of Fibonacci using Recursion</h3><hr
/> Yes, that is surprisingly it. Now you see why recursion can make our life a bit easier sometimes? If you don&#8217;t understand how it works, look at the following set of images. Try drawing them out by hand to understand how they work.<br
/> <br/></p><p><center><br
/> <a
href="http://talkbinary.com/wp-content/uploads/2010/02/fib02.jpg"><img
src="http://talkbinary.com/wp-content/uploads/2010/02/fib02.jpg" alt="" title="fib02" width="290" height="173" class="aligncenter size-full wp-image-2259" /></a></p><p><a
href="http://talkbinary.com/wp-content/uploads/2010/02/fib03.jpg"><img
src="http://talkbinary.com/wp-content/uploads/2010/02/fib03-300x219.jpg" alt="" title="fib03" width="300" height="219" class="aligncenter size-medium wp-image-2260" /></a></center></p><p>The following image shows you how the recursive calls would be made with larger n values.</p><p><center><a
href="http://talkbinary.com/wp-content/uploads/2010/02/fib04.jpg"><img
src="http://talkbinary.com/wp-content/uploads/2010/02/fib04-300x119.jpg" alt="" title="fib04" width="300" height="119" class="aligncenter size-medium wp-image-2261" /></a></center></p><p><br/></p><h3>Overview of Fibonacci Sequence using Recursion</h3><hr
/> If you still don&#8217;t understand how it works, my best encouragement is to draw the function calls by hand. Try doing something similar to my drawings. Recursion is a tough topic so it takes some time to learn. Even I struggled with the subject.</p><p>If you have any questions or suggestions, feel free to post them below.</p><h3  class="related_post_title">Related Posts</h3><ul
class="related_post"><li><a
href="http://talkbinary.com/programming/c/c-recursion-reverse-elements-of-a-vector/" title="C++ Recursion &#8211; Reverse elements of a vector">C++ Recursion &#8211; Reverse elements of a vector</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-power-continued/" title="C++ Recursion &#8211; Power Continued">C++ Recursion &#8211; Power Continued</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-power/" title="C++ Recursion &#8211; Power">C++ Recursion &#8211; Power</a> (1)</li><li><a
href="http://talkbinary.com/programming/c/special-functions/fibonacci-in-c/" title="Fibonacci in C++">Fibonacci in C++</a> (3)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-palindrome/" title="C++ Recursion &#8211; Palindrome">C++ Recursion &#8211; Palindrome</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-factorial/" title="C++ Recursion &#8211; Factorial">C++ Recursion &#8211; Factorial</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-summation/" title="C++ Recursion &#8211; Summation ">C++ Recursion &#8211; Summation </a> (2)</li><li><a
href="http://talkbinary.com/programming/c/introduction-to-recursion-in-c/" title="Introduction to Recursion in C++">Introduction to Recursion in C++</a> (6)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion/" title="C++ Recursion">C++ Recursion</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-greatest-common-divisor/" title="C++ Recursion &#8211; Greatest Common Divisor ">C++ Recursion &#8211; Greatest Common Divisor </a> (0)</li></ul>]]></content:encoded> <wfw:commentRss>http://talkbinary.com/programming/c/c-recursion-fibonacci/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Tail Recursion</title><link>http://talkbinary.com/programming/c/c-tail-recursion/</link> <comments>http://talkbinary.com/programming/c/c-tail-recursion/#comments</comments> <pubDate>Thu, 14 May 2009 18:54:06 +0000</pubDate> <dc:creator>Diego</dc:creator> <category><![CDATA[C++]]></category> <category><![CDATA[ML]]></category> <category><![CDATA[c++ factorial]]></category> <category><![CDATA[c++ recursion]]></category> <category><![CDATA[factorial]]></category> <category><![CDATA[ml factorial]]></category> <category><![CDATA[ml recursion]]></category> <category><![CDATA[recursion]]></category> <category><![CDATA[recursion c++]]></category> <category><![CDATA[recursive function]]></category> <category><![CDATA[tail]]></category> <category><![CDATA[tail recursion]]></category><guid
isPermaLink="false">http://talkbinary.com/?p=1647</guid> <description><![CDATA[Overview of Tail Recursion Tail Recursion is simply a special form of recursion, in which the recursive call is at the end of the function. This allows for improved efficiency as the final value to be computed is returned without any further calculation when the recursion function terminates. Factorial without Tail Recursion in C++ First [...]]]></description> <content:encoded><![CDATA[<blockquote><h3>Overview of Tail Recursion</h3><p> Tail Recursion is simply a special form of recursion, in which the recursive call is at the end of the function. This allows for improved efficiency as the final value to be computed is returned without any further calculation when the recursion function terminates.</p></blockquote><h4>Factorial without Tail Recursion in C++</h4><p> First a version without tail recursion will be shown in C++. This version requires that the function has to compute a new value to return to it&#8217;s caller after the function it called returned a value.</p><pre lang="c++">int fact(int n) {
     if ( n <= 1 ) return n;

     return n  * fact(n-1);
}</pre><p><br/></p><h4>Factorial with Tail Recursion in C++</h4><p>Below is the factorial function with tail recursion. Can you tell the difference from the one posted above? The function below doesn't need to do any more computations when the function it called returns (considering its not the last function that was called). It simply returns the value without any further calculation.</p><p>Usually, if it can be done using tail recursion, the function can be iteratively solved as well.</p><pre lang="c++">int fact(int n) {
     return fact_h(n, 1);
}

int fact_h(int n, int res) {
   if ( n <= 1 ) return res;

   return fact_h(n-1, n*res);
}</pre><h3>Tail Recursion in a functional language</h3><p>In C++, if you can write a tail recursive function most likely you can right an iterative version. In a functional language where iteration isn't possible, tail recursion allows for greater efficiency in such functions.</p><p><span
id="more-1647"></span></p><h4>Recursive function in ML without tail recursion</h4><p>Below is a factorial function in <a
href="http://talkbinary.com/programming/start-programming-in-ml/">ML</a>. This version does not implement tail recursion.</p><div
class="wp_syntax"><div
class="code"><pre class="sml" style="font-family:monospace;">fun fact 1  = 1 
| fact x = x * fact (x-1);</pre></div></div><p><br/></p><h4>Implementing Tail Recursion in ML</h4><p>The function below, does implement tail recursion. If you notice, this function does not require to do any computations after the function has returned as the function in the previous version.</p><div
class="wp_syntax"><div
class="code"><pre class="ml" style="font-family:monospace;">fun facth 1 n = n
| facth x n = facth (x-1) (n*x);
&nbsp;
fun fact 1 = 1
| fact x = facth x 1;</pre></div></div><h3>Overview of Tail Recursion</h3><p>So why is this faster? Well, first of all, it means you are uses the stack less, thus increasing efficiency. If you can implement tail recursion in a programming language such as C++, there must be an iterative version of the function. On the other hand if you are creating functions in a logic or functional programming language, try using tail recursion. On large projects you'll notice a great improvement in runtime.</p><h3  class="related_post_title">Related Posts</h3><ul
class="related_post"><li><a
href="http://talkbinary.com/programming/c/c-recursion/" title="C++ Recursion">C++ Recursion</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-palindrome/" title="C++ Recursion &#8211; Palindrome">C++ Recursion &#8211; Palindrome</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-logarithm/" title="C++ Recursion &#8211; Logarithm">C++ Recursion &#8211; Logarithm</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-greatest-common-divisor/" title="C++ Recursion &#8211; Greatest Common Divisor ">C++ Recursion &#8211; Greatest Common Divisor </a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-power-continued/" title="C++ Recursion &#8211; Power Continued">C++ Recursion &#8211; Power Continued</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-power/" title="C++ Recursion &#8211; Power">C++ Recursion &#8211; Power</a> (1)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-factorial/" title="C++ Recursion &#8211; Factorial">C++ Recursion &#8211; Factorial</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-helper-functions/" title="C++ Helper Functions">C++ Helper Functions</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/introduction-to-recursion-in-c/" title="Introduction to Recursion in C++">Introduction to Recursion in C++</a> (6)</li><li><a
href="http://talkbinary.com/programming/c/recursion-examples/" title="C++ Recursion Examples">C++ Recursion Examples</a> (0)</li></ul>]]></content:encoded> <wfw:commentRss>http://talkbinary.com/programming/c/c-tail-recursion/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>C++ Helper Functions</title><link>http://talkbinary.com/programming/c/c-helper-functions/</link> <comments>http://talkbinary.com/programming/c/c-helper-functions/#comments</comments> <pubDate>Mon, 13 Apr 2009 07:03:24 +0000</pubDate> <dc:creator>Diego</dc:creator> <category><![CDATA[C++]]></category> <category><![CDATA[c++ recursion]]></category> <category><![CDATA[functions]]></category> <category><![CDATA[helper]]></category> <category><![CDATA[helper functions]]></category> <category><![CDATA[print]]></category> <category><![CDATA[recursion c++]]></category> <category><![CDATA[vector]]></category><guid
isPermaLink="false">http://talkbinary.com/?p=1691</guid> <description><![CDATA[Overview A helper function is merely a function that passes additional arguments to another function of a similar name. The additional arguments that are passed in are usually predetermined by the programmer that allow the use of recursion. This tutorial considers you are knowledgeable with recursion since our example deals with a recursive function. Example [...]]]></description> <content:encoded><![CDATA[<h3>Overview</h3><p>A helper function is merely a function that passes additional arguments to another function of a similar name. The additional arguments that are passed in are usually predetermined by the programmer that allow the use of recursion.</p><p>This tutorial considers you are knowledgeable with <a
href="http://talkbinary.com/programming/c/introduction-to-recursion-in-c/">recursion</a> since our example deals with a recursive function.</p><h3>Example of a helper function</h3><p>Below we&#8217;ll provide you an example of when you might encounter the use of a helper function. We&#8217;ll start off by introducing a simple print function that prints all the elements of a vector.</p><pre lang="c++">void print(vector <int> vec) { 

     for ( int i = 0; i < vec.size(); i++ ) {
          cout << i << ": " << vec[i] << endl;
     }
}</pre><p><br/><br
/> This function would be called in your main program in the following way.</p><pre lang="c++">
#include <iostream>
#include <vector>

using namespace std;

int main() { 

     vector <int> vec;

     /* Fill the vector with values...using push_back() perhaps? */

     //Calling of our function
     print(vec);

     return 0;
}</pre><p><br/></p><h4>Where the helper function comes in</h4><p>Now, imagine for some reason you want to try making your print function recursively. The thing is, if you want to print using recursion, you need your function to have an additional parameter in order to track what element we are currently printing.<br
/> <span
id="more-1691"></span><br
/> This would mean that we would have to change all our calls to our print function to include an additional parameter.  Well, we don't if we use a helper function. By simply having our original print function call our helper function, we avoid changing the names of all our calls.</p><pre lang="c++">void print(vector <int> vec) { 

     print_h(vec, 0);

}

void print_h(vector <int> vec, int i) { 

    if ( i > vec.size() ) {
        return;
    }

    cout << i << ": " << vec[i] << endl;

    print(vec, i+1);

    return;
}</pre><h3  class="related_post_title">Related Posts</h3><ul
class="related_post"><li><a
href="http://talkbinary.com/programming/c/c-tail-recursion/" title="Tail Recursion">Tail Recursion</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion/" title="C++ Recursion">C++ Recursion</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-binary-search/" title="C++ Recursion &#8211; Binary Search">C++ Recursion &#8211; Binary Search</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-logarithm/" title="C++ Recursion &#8211; Logarithm">C++ Recursion &#8211; Logarithm</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-palindrome/" title="C++ Recursion &#8211; Palindrome">C++ Recursion &#8211; Palindrome</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-reverse-elements-of-a-vector/" title="C++ Recursion &#8211; Reverse elements of a vector">C++ Recursion &#8211; Reverse elements of a vector</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-printing-elements-of-a-vector/" title="C++ Recursion &#8211; Printing Elements of a Vector">C++ Recursion &#8211; Printing Elements of a Vector</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/introduction-to-recursion-in-c/" title="Introduction to Recursion in C++">Introduction to Recursion in C++</a> (6)</li><li><a
href="http://talkbinary.com/programming/c/functions-in-c/" title="Introduction to Functions ">Introduction to Functions </a> (0)</li><li><a
href="http://talkbinary.com/programming/c/simple-data-structure-the-vector/" title="Simple Data Structure &#8211; The Vector">Simple Data Structure &#8211; The Vector</a> (4)</li></ul>]]></content:encoded> <wfw:commentRss>http://talkbinary.com/programming/c/c-helper-functions/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Introduction to Recursion in C++</title><link>http://talkbinary.com/programming/c/introduction-to-recursion-in-c/</link> <comments>http://talkbinary.com/programming/c/introduction-to-recursion-in-c/#comments</comments> <pubDate>Sat, 21 Feb 2009 23:18:23 +0000</pubDate> <dc:creator>Diego</dc:creator> <category><![CDATA[C++]]></category> <category><![CDATA[activation records]]></category> <category><![CDATA[base case]]></category> <category><![CDATA[c++ recursion]]></category> <category><![CDATA[display function]]></category> <category><![CDATA[recursion]]></category> <category><![CDATA[recursive]]></category> <category><![CDATA[stack]]></category> <category><![CDATA[terminating condition]]></category><guid
isPermaLink="false">http://talkbinary.com/?p=1572</guid> <description><![CDATA[Recursion in C++ is simply a function that calls itself that terminates when a base case is met. ]]></description> <content:encoded><![CDATA[<p>Recursion in C++ is simply a function that calls itself that terminates when a base case is met. It&#8217;s very useful to learn how recursion for a couple of reasons.</p><ul><li>It&#8217;s easier to solve certain problems with recursion as the resulting code is usually shorter</li><li>Sometimes its the only way</li></ul><h3>Displaying numbers recursively</h3><p>So what&#8217;s an example of a recursive function? Let&#8217;s make one. Let&#8217;s start by creating a function that displays a number (it isn&#8217;t the best example, but it&#8217;s good enough to introduce you to recursion).</p><h4>Display Function</h4><div
class="wp_syntax"><table><tr><td
class="line_numbers"><pre>1
2
3
4
5
</pre></td><td
class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">void</span> display<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> n<span style="color: #008000;">&#41;</span> 
<span style="color: #008000;">&#123;</span>
     <span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> n <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot; &quot;</span><span style="color: #008080;">;</span>
     <span style="color: #0000ff;">return</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div><p><br/>All this function does is simply print the number passed in.</p><h4>Recursive Display Function</h4><p>Now let&#8217;s have this function call itself but lets decrement the value being displayed each time.</p><div
class="wp_syntax"><table><tr><td
class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td
class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">void</span> display<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> n<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
     <span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> n <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot; &quot;</span><span style="color: #008080;">;</span>
     display<span style="color: #008000;">&#40;</span>n<span style="color: #000040;">-</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> <span style="color: #666666;">//Will call display but with (n-1)</span>
     <span style="color: #0000ff;">return</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div><p>So let&#8217;s say we executed display(10)</p><p>What would this display? It would display 10 9 8 7 6 5 4&#8230;and would never stop. Why? We never told the function when to terminate. This will either cause your program to run until you kill it, or may cause it to segmentation fault. In order to fix this, this calls for the addition of <strong>base case</strong>. <span
id="more-1572"></span></p><blockquote><h3>Base Cases in Recursion</h3><p>In order for your recursive function to terminate you <strong>always</strong> need a base case. You may have multiple base cases.</p></blockquote><h4>Recursive Display Function with a Base Case</h4><p>Let&#8217;s make the function terminate when n is 0. Or better yet, let&#8217;s make it terminate when n is less than or equal to 0. (Why do you think this is better?)</p><div
class="wp_syntax"><table><tr><td
class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td
class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">void</span> display<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> n<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
     <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span> n <span style="color: #000080;">&lt;=</span> <span style="color: #0000dd;">0</span> <span style="color: #008000;">&#41;</span> <span style="color: #0000ff;">return</span><span style="color: #008080;">;</span> 
     <span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> n <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot; &quot;</span><span style="color: #008080;">;</span>
     display<span style="color: #008000;">&#40;</span>n<span style="color: #000040;">-</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> <span style="color: #666666;">//Will call display but with (n-1)</span>
     <span style="color: #0000ff;">return</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div><p>So now, if we execute display(10), what would it display?</p><pre lang="c++">10 9 8 7 6 5 4 3 2 1 </pre><h3>How Recursion works in C++</h3><p>So how does recursion work in C++? Each <strong>function</strong> creates an activation record on the <strong>stack</strong>. As a function gets called, it gets added to the top of the stack. Until the function is terminated, is then taken off the stack. A visual example for our display function is below.</p><p><center><div
id="attachment_1594" class="wp-caption alignnone" style="width: 245px"><a
href="http://talkbinary.com/wp-content/uploads/2009/02/recursion.jpg"><img
src="http://talkbinary.com/wp-content/uploads/2009/02/recursion-235x300.jpg" alt="Click to Enlarge" title="recursion" width="235" height="300" class="size-medium wp-image-1594" /></a><p
class="wp-caption-text">(Click to Enlarge)</p></div></center></p><p>The first function called was display(10) which is the activation record seen at the bottom of our stack. If you notice, the following function keep getting called as long as the base case isn&#8217;t met. Up until n = -1, then the activation record of the functions are popped off.</p><h3>Comments on Recursion</h3><p>What is shown previously is a very basic recursive algorithm. More recursion techniques will be discussed later. So even if you don&#8217;t understand the purpose of recursion just yet, don&#8217;t hesitate. You&#8217;ll understand why it&#8217;s important when you understand recursion is the only way to do certain problems.</p><h3  class="related_post_title">Related Posts</h3><ul
class="related_post"><li><a
href="http://talkbinary.com/programming/c/c-recursion/" title="C++ Recursion">C++ Recursion</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-palindrome/" title="C++ Recursion &#8211; Palindrome">C++ Recursion &#8211; Palindrome</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-reverse-elements-of-a-vector/" title="C++ Recursion &#8211; Reverse elements of a vector">C++ Recursion &#8211; Reverse elements of a vector</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-fibonacci/" title="C++ Recursion &#8211; Fibonacci">C++ Recursion &#8211; Fibonacci</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-printing-elements-of-a-vector/" title="C++ Recursion &#8211; Printing Elements of a Vector">C++ Recursion &#8211; Printing Elements of a Vector</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-factorial/" title="C++ Recursion &#8211; Factorial">C++ Recursion &#8211; Factorial</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/c-recursion-summation/" title="C++ Recursion &#8211; Summation ">C++ Recursion &#8211; Summation </a> (2)</li><li><a
href="http://talkbinary.com/programming/c/c-tail-recursion/" title="Tail Recursion">Tail Recursion</a> (0)</li><li><a
href="http://talkbinary.com/programming/c/special-functions/fibonacci-in-c/" title="Fibonacci in C++">Fibonacci in C++</a> (3)</li><li><a
href="http://talkbinary.com/programming/c/recursion-examples/" title="C++ Recursion Examples">C++ Recursion Examples</a> (0)</li></ul>]]></content:encoded> <wfw:commentRss>http://talkbinary.com/programming/c/introduction-to-recursion-in-c/feed/</wfw:commentRss> <slash:comments>6</slash:comments> </item> </channel> </rss>
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk
Page Caching using disk (enhanced) (user agent is rejected)
Database Caching 66/157 queries in 0.638 seconds using disk

Served from: talkbinary.com @ 2010-07-31 10:08:33 -->