<?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; recursive function</title>
	<atom:link href="http://talkbinary.com/tag/recursive-function/feed/" rel="self" type="application/rss+xml" />
	<link>http://talkbinary.com</link>
	<description>Programming Resources, Technology, Computers</description>
	<lastBuildDate>Mon, 06 Feb 2012 17:01:43 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.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<a class="moretag" href="http://talkbinary.com/programming/c/c-recursion/">&#160;&#160;Full Article&#8230;</a>
]]></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 id="section-1">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 id="section-2">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 id="section-3">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 id="section-4">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>
]]></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<a class="moretag" href="http://talkbinary.com/programming/c/c-recursion-binary-search/">&#160;&#160;Full Article&#8230;</a>
]]></description>
			<content:encoded><![CDATA[<h2 id="section-1">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 id="section-2">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 id="section-3">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 id="section-4">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 id="section-5">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 id="section-6">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 id="section-7">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>
]]></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[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<a class="moretag" href="http://talkbinary.com/programming/c/c-recursion-logarithm/">&#160;&#160;Full Article&#8230;</a>
]]></description>
			<content:encoded><![CDATA[<h2 id="section-1">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 id="section-2">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>[pmath]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 />
[/pmath]<br />
<br/>
</p></blockquote>
<h2 id="section-3">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 id="section-4">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 id="section-5">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 id="section-6">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 id="section-5">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 id="section-8">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>
]]></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[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.<a class="moretag" href="http://talkbinary.com/programming/c/c-recursion-palindrome/">&#160;&#160;Full Article&#8230;</a>
]]></description>
			<content:encoded><![CDATA[<h2 id="section-1">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 id="section-2">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 id="section-3"> 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 id="section-4">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 id="section-5">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 id="section-6">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 id="section-7">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 id="section-8">string::subtr</h2>
<p>The <strong>substr</strong> functions returns a substring with the following parameters of the current object. </p>
<blockquote><h3 id="section-9">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 id="section-10">Return value of substr</h4>
<p>A <strong>string</strong> containing the substring of the object.</p>
<h4 id="section-11">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 id="section-12">Going further</h3>
<ol>
<li>Can you apply this using a vector?</li>
</ol>
]]></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; Greatest Common Divisor</title>
		<link>http://talkbinary.com/programming/c/c-recursion-greatest-common-divisor/</link>
		<comments>http://talkbinary.com/programming/c/c-recursion-greatest-common-divisor/#comments</comments>
		<pubDate>Mon, 08 Mar 2010 05:32:49 +0000</pubDate>
		<dc:creator>Diego</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[euclidean algorithm]]></category>
		<category><![CDATA[function]]></category>
		<category><![CDATA[gcd]]></category>
		<category><![CDATA[greatest common divisor]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[recursive function]]></category>

		<guid isPermaLink="false">http://talkbinary.com/?p=2292</guid>
		<description><![CDATA[Greatest Common Divisor using the Euclidean Algorithm Below is an example of how to create the recursive function of computing the greatest common divisor using the Euclidean Algorithm. * This tutorial assumes you understand the following. Introduction to Recursion in C++ Euclid&#8217;s Algorithm When studying computer science a famous algorithm taught to students is the<a class="moretag" href="http://talkbinary.com/programming/c/c-recursion-greatest-common-divisor/">&#160;&#160;Full Article&#8230;</a>
]]></description>
			<content:encoded><![CDATA[<h2 id="section-1">Greatest Common Divisor using the Euclidean Algorithm</h2>
<hr />
Below is an example of how to create the recursive function of computing the <strong>greatest common diviso</strong>r using the Euclidean Algorithm.<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>
<h3 id="section-2">Euclid&#8217;s Algorithm</h3>
<p>When studying computer science a famous algorithm taught to students is the <a href="http://en.wikipedia.org/wiki/Euclidean_algorithm">Euclidean Algorithm</a> which is used to compute the greatest common divisor of two integers. It&#8217;s definition is below. </p>
<p>[pmath] gcd(x,y) [/pmath]</p>
<p><img src="http://talkbinary.com/wp-content/uploads/2010/03/euclid1.png" alt="" title="euclid1" width="146" height="17" class="aligncenter size-full wp-image-2310" /></p>
<p><img src="http://talkbinary.com/wp-content/uploads/2010/03/euclid2.png" alt="" title="euclid2" width="390" height="63" class="aligncenter size-full wp-image-2311" />
</p></blockquote>
<h2 id="section-3">Computing various examples</h2>
<hr />
So how does it work? Well, let&#8217;s follow the definition, but before doing that, do you remember how to compute the remainder of two integers in c++? If you don&#8217;t, well it&#8217;s the <strong>%</strong> (mod) operator.<br />
<br/></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: #666666;">// Computing the gcd of 45 and 9 //</span>
gcd<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">45</span>, <span style="color: #0000dd;">9</span><span style="color: #008000;">&#41;</span> 
<span style="color: #000080;">=</span> gcd<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">9</span>, <span style="color: #0000dd;">45</span> <span style="color: #000040;">%</span> <span style="color: #0000dd;">9</span> <span style="color: #008000;">&#41;</span> <span style="color: #000080;">=</span> gcd<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">9</span>, <span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span> 
<span style="color: #000080;">=</span> <span style="color: #0000dd;">9</span>
&nbsp;
&nbsp;
<span style="color: #666666;">// Computing the gcd of 54 and 12 //</span>
gcd<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">54</span>, <span style="color: #0000dd;">12</span><span style="color: #008000;">&#41;</span>
<span style="color: #000080;">=</span> gcd<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">12</span>, <span style="color: #0000dd;">54</span> <span style="color: #000040;">%</span> <span style="color: #0000dd;">12</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">=</span> gcc<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">12</span>, <span style="color: #0000dd;">6</span><span style="color: #008000;">&#41;</span> 
<span style="color: #000080;">=</span> gcd<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">6</span>, <span style="color: #0000dd;">12</span> <span style="color: #000040;">%</span> <span style="color: #0000dd;">6</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">=</span> gcd<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">6</span>, <span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span>
<span style="color: #000080;">=</span> <span style="color: #0000dd;">6</span></pre></td></tr></table></div>

<p><br/><span id="more-2292"></span><br />
Now that you saw how this works, try creating the recursive function for the greatest common divisor by simply using the definition. <strong>[Hint: Treat the Conditions as your base cases]</strong></p>
<h2 id="section-4">Recursive function of Greatest Common Divisor</h2>
<hr />
The solution for the function is below. If you notice you&#8217;ll see that the definition was simply translated into a recursive c++ function aside from an additional base case that handles erroneous input.<br />
<br/></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
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">int</span> gcd<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> x, <span style="color: #0000ff;">int</span> y<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> 
&nbsp;
     <span style="color: #666666;">// Condition 1 //</span>
     <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span> y <span style="color: #000080;">==</span> <span style="color: #0000dd;">0</span> <span style="color: #008000;">&#41;</span> 
          <span style="color: #0000ff;">return</span> x<span style="color: #008080;">;</span> 
&nbsp;
     <span style="color: #666666;">// Condition 2 // </span>
     <span style="color: #0000ff;">else</span> <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span> x <span style="color: #000080;">&gt;=</span> y <span style="color: #000040;">&amp;&amp;</span> y <span style="color: #000080;">&gt;</span> <span style="color: #0000dd;">0</span> <span style="color: #008000;">&#41;</span> 
          <span style="color: #0000ff;">return</span> gcd<span style="color: #008000;">&#40;</span>y, x<span style="color: #000040;">%</span>y<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
     <span style="color: #666666;">// If not condition was met return error //</span>
     <span style="color: #0000ff;">else</span> 
         <span style="color: #0000ff;">return</span> <span style="color: #000040;">-</span><span style="color: #0000dd;">1</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p><br/></p>
<h2 id="section-5">Going further</h2>
<hr />
<ol>
<li>Can you figure a way to make sure x is always the larger value? <strong>[Hint: <a href="http://talkbinary.com/programming/c/c-helper-functions/">C++ Helper Functions</a>]</strong></li>
<li>Can you write the iterative version?</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://talkbinary.com/programming/c/c-recursion-greatest-common-divisor/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>C++ Recursion &#8211; Power Continued</title>
		<link>http://talkbinary.com/programming/c/c-recursion-power-continued/</link>
		<comments>http://talkbinary.com/programming/c/c-recursion-power-continued/#comments</comments>
		<pubDate>Fri, 12 Feb 2010 06:35:04 +0000</pubDate>
		<dc:creator>Diego</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[function]]></category>
		<category><![CDATA[iteration]]></category>
		<category><![CDATA[iterative]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[power function]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[recursive function]]></category>

		<guid isPermaLink="false">http://talkbinary.com/?p=2157</guid>
		<description><![CDATA[Creating a power function using Recursion So, previously we tried computing the Power function using recursion but we didn&#8217;t take into account when the exponent was negative. This continues the previous function, so if you haven&#8217;t yet, go back. Make sure you understand the following as well: C++ Recursion C++ Recursion &#8211; Summation C++ Recursion<a class="moretag" href="http://talkbinary.com/programming/c/c-recursion-power-continued/">&#160;&#160;Full Article&#8230;</a>
]]></description>
			<content:encoded><![CDATA[<h3 id="section-1">Creating a power function using Recursion</h3>
<hr />
So, previously we tried computing the <a href="http://talkbinary.com/programming/c/c-recursion-power/">Power</a> function using recursion but we didn&#8217;t take into account when the exponent was negative. This continues the previous function, so if you haven&#8217;t yet, go back. Make sure you understand the following as well:</p>
<ol>
<li><a href="http://talkbinary.com/programming/c/introduction-to-recursion-in-c/">C++ Recursion</a></li>
<li><a href="http://talkbinary.com/programming/c/c-recursion-summation/">C++ Recursion &#8211; Summation</a></li>
<li><a href="http://talkbinary.com/programming/c/c-recursion-factorial/">C++ Recursion &#8211; Factorial</a></li>
</ol>
<h3 id="section-2">Power Function using Recursion</h3>
<hr/>
Below is our previous power function which takes into account only positive exponents. So how would we go on by taking into account negative exponents?<br />
<br/></p>
<pre lang="c++">int power(int base, int exp) {

     //Return 1 when n is 0
     if ( n == 0 )
          return 1;
     else if ( n == 1 )
           return base;
     else
          return base * power(base, exp-1);
     int result = base;

}</pre>
<p><br/></p>
<p>Let&#8217;s start by coming up with a formula again. </p>
<pre lang="c++">power(2,-1) = (1/2);

power(2,-2) = (1/2) * power(2, -1) = (1/2) * (1/2) = (1/4);

power(2,-3) = (1/2) * power(2,-2) = (1/2) * (1/4) = (1/8);

power(2,-4) = (1/2) * power(2,-3) = (1/2) * (1/8) = (1/16);

...

//Until exp == -1
power(base, -exp) = (1/base) * power(base, exp+1);</pre>
<p><br/></p>
<h3 id="section-3">Taking into account negative exponents</h3>
<hr />
So now that we have a formula, what would be our base case? We surely don&#8217;t want our previous base case to return 1 when (n==0) because that would be wrong.<br />
<span id="more-2157"></span><br />
<br/></p>
<pre lang="c++">if ( exp == -1 ) return (1/base);</pre>
<p><br/></p>
<p>Then simply applying the formula to do the computation of other values below -1:</p>
<pre lang="c++">int power(int base, int exp) {

      if ( n < - 1)
          return (1/base) * power(base, exp+1);
     else if ( n == -1 )
          return (1/base);
     //Return 1 when n is 0
     else if ( n == 0 )
          return 1;
     else if ( n == 1 )
           return base;
     else
          return base * power(base, exp-1);
     int result = base;

}</pre>
<p><br/><br />
Now try it. Does it work? </p>
<h3 id="section-4">Finalizing the Power Function using Recursion</h3>
<hr />
Unfortunately, this won't work. Whenever you try computing the power of lets say <b><i>power(2,-3)</i></b> you will receive 0. Why? Because when you divide and have an int as one of the operands, an int is returned. Below is the fix. If you want to return a double, make sure both your operands are doubles.<br />
<br/></p>
<pre lang="c++">int power(int base, int exp) {

      if ( n < - 1)
          return (1.0/base) * power(base, exp+1);
     //Return (1.0/base) when n == -1
     else if ( n == -1 )
          return (1.0/base);
     //Return 1 when n is 0
     else if ( n == 0 )
          return 1;
     else if ( n == 1 )
           return base;
     else
          return base * power(base, exp-1);
     int result = base;

}</pre>
<p><br/><br />
By this time you should be able to work out similar problems involving recursion. Make sure you are truly grasping the subject. If not, feel free to ask questions.</p>
]]></content:encoded>
			<wfw:commentRss>http://talkbinary.com/programming/c/c-recursion-power-continued/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C++ Recursion &#8211; Power</title>
		<link>http://talkbinary.com/programming/c/c-recursion-power/</link>
		<comments>http://talkbinary.com/programming/c/c-recursion-power/#comments</comments>
		<pubDate>Mon, 08 Feb 2010 03:41:54 +0000</pubDate>
		<dc:creator>Diego</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[function]]></category>
		<category><![CDATA[iteration]]></category>
		<category><![CDATA[iterative]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[power function]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[recursive function]]></category>

		<guid isPermaLink="false">http://talkbinary.com/?p=2104</guid>
		<description><![CDATA[Creating a power function using Recursion Below is an example of how to calculate the x to the power of n. This tutorial expects you to understand the following: C++ Recursion C++ Recursion &#8211; Summation C++ Recursion &#8211; Factorial Example: 1 2 pow&#40;2,3&#41;; pow&#40;5,4&#41;; Result: 1 2 8 625 Iterative version of a function that<a class="moretag" href="http://talkbinary.com/programming/c/c-recursion-power/">&#160;&#160;Full Article&#8230;</a>
]]></description>
			<content:encoded><![CDATA[<h3 id="section-1">Creating a power function using Recursion</h3>
<hr />
Below is an example of how to calculate the x to the power of n. This tutorial expects you to understand the following: </p>
<ol>
<li><a href="http://talkbinary.com/programming/c/introduction-to-recursion-in-c/">C++ Recursion</a></li>
<li><a href="http://talkbinary.com/programming/c/c-recursion-summation/">C++ Recursion &#8211; Summation</a></li>
<li><a href="http://talkbinary.com/programming/c/c-recursion-factorial/">C++ Recursion &#8211; Factorial</a></li>
</ol>
<p>Example:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000dd;">pow</span><span style="color: #008000;">&#40;</span><span style="color: #0000dd;">2</span>,<span style="color: #0000dd;">3</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #0000dd;">pow</span><span style="color: #008000;">&#40;</span><span style="color: #0000dd;">5</span>,<span style="color: #0000dd;">4</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></pre></td></tr></table></div>

<p>Result:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000dd;">8</span>
<span style="color: #0000dd;">625</span></pre></td></tr></table></div>

<h3 id="section-2">Iterative version of a function that calculates the power function</h3>
<hr />
To understand how to calculate the power function using recursion, let&#8217;s write a simple algorithm that will do it for us using iteration.<br />
<br/></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
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">int</span> power<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> base, <span style="color: #0000ff;">int</span> <span style="color: #0000dd;">exp</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
&nbsp;
     <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span> <span style="color: #0000dd;">exp</span> <span style="color: #000080;">==</span> <span style="color: #0000dd;">0</span> <span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
          <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">1</span><span style="color: #008080;">;</span> 
     <span style="color: #008000;">&#125;</span>
&nbsp;
     <span style="color: #666666;">//Initial value for the result is the base</span>
     <span style="color: #0000ff;">int</span> result <span style="color: #000080;">=</span> base<span style="color: #008080;">;</span>
&nbsp;
     <span style="color: #666666;">//Multiplies the base by itself exp number of times</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> <span style="color: #0000dd;">exp</span><span style="color: #008080;">;</span> i<span style="color: #000040;">++</span> <span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> 
          result <span style="color: #000080;">=</span> result <span style="color: #000040;">*</span> base<span style="color: #008080;">;</span> 
     <span style="color: #008000;">&#125;</span>
&nbsp;
     <span style="color: #0000ff;">return</span> result<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p><span id="more-2104"></span></p>
<h3 id="section-3">Calculating the power function using recursion</h3>
<hr />
So how would we go by solving this using recursion? First of all we need a function header.</p>
<p><br/></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;"><span style="color: #0000ff;">int</span> power<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> base, <span style="color: #0000ff;">int</span> <span style="color: #0000dd;">exp</span><span style="color: #008000;">&#41;</span></pre></td></tr></table></div>

<p><br/></p>
<p>Next, what would be our base case? When we are trying to calculate n to the power of 0, the result should be 1. Also, when we try calculating n to the power of 1, the result should be n.</p>
<p><br/></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;">int</span> power<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> base, <span style="color: #0000ff;">int</span> <span style="color: #0000dd;">exp</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
&nbsp;
     <span style="color: #666666;">//Return 1 when n is 0</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;">1</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> base<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p><br/></p>
<p>Now, how would we go on by computing the power function using recursion? Let&#8217;s come up with a formula by calculating 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
12
13
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;">power<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">2</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: #008080;">;</span>
&nbsp;
power<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">2</span>,<span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">2</span><span style="color: #008080;">;</span>
&nbsp;
power<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">2</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> power<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">2</span>,<span style="color: #0000dd;">1</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;">2</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">4</span><span style="color: #008080;">;</span>
&nbsp;
power<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">2</span>,<span style="color: #0000dd;">3</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">2</span> <span style="color: #000040;">*</span> power<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">2</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;">4</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">8</span><span style="color: #008080;">;</span>
&nbsp;
power<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">2</span>,<span style="color: #0000dd;">4</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">2</span> <span style="color: #000040;">*</span> power<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">2</span>,<span style="color: #0000dd;">3</span><span style="color: #008000;">&#41;</span> <span style="color: #0000dd;">2</span> <span style="color: #000040;">*</span> <span style="color: #0000dd;">8</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">16</span><span style="color: #008080;">;</span>
&nbsp;
...
&nbsp;
<span style="color: #007788;">power</span><span style="color: #008000;">&#40;</span>base, <span style="color: #0000dd;">exp</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">=</span> base <span style="color: #000040;">*</span> power<span style="color: #008000;">&#40;</span>base, exp<span style="color: #000040;">-</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></pre></td></tr></table></div>

<p><br/><br />
Translating the above formula to code, is then fairly trivial. This would allow us to apply our power function to any two positive integers.<br />
<br/></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">int</span> power<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> base, <span style="color: #0000ff;">int</span> <span style="color: #0000dd;">exp</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
&nbsp;
     <span style="color: #666666;">//Return 1 when n is 0</span>
     <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span> <span style="color: #0000dd;">exp</span> <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;">1</span><span style="color: #008080;">;</span>
     <span style="color: #0000ff;">else</span> <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span> <span style="color: #0000dd;">exp</span> <span style="color: #000080;">==</span> <span style="color: #0000dd;">1</span> <span style="color: #008000;">&#41;</span> 
           <span style="color: #0000ff;">return</span> base<span style="color: #008080;">;</span>
     <span style="color: #0000ff;">else</span> 
          <span style="color: #0000ff;">return</span> base <span style="color: #000040;">*</span> power<span style="color: #008000;">&#40;</span>base, exp<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;">int</span> result <span style="color: #000080;">=</span> base<span style="color: #008080;">;</span>
&nbsp;
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p><br/></p>
<p>Have any questions? Feel free to ask below or request any other examples.</p>
<h3 id="section-4">Going further</h3>
<hr />
<ul>
<li>1. How would you make this function take care of negative exponents?</li>
]]></content:encoded>
			<wfw:commentRss>http://talkbinary.com/programming/c/c-recursion-power/feed/</wfw:commentRss>
		<slash:comments>4</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<a class="moretag" href="http://talkbinary.com/programming/c/c-tail-recursion/">&#160;&#160;Full Article&#8230;</a>
]]></description>
			<content:encoded><![CDATA[<blockquote><h3 id="section-1">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 id="section-2">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 id="section-3">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 id="section-4">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 id="section-5">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 id="section-6">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 id="section-1">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>
]]></content:encoded>
			<wfw:commentRss>http://talkbinary.com/programming/c/c-tail-recursion/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Page Caching using disk: enhanced

Served from: talkbinary.com @ 2012-02-12 01:15:16 -->
