<?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; recursion</title>
	<atom:link href="http://talkbinary.com/tag/recursion/feed/" rel="self" type="application/rss+xml" />
	<link>http://talkbinary.com</link>
	<description>Programming Resources, Technology, Computers</description>
	<lastBuildDate>Wed, 15 Feb 2012 16:01:31 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</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 Examples</title>
		<link>http://talkbinary.com/programming/c/recursion-examples/</link>
		<comments>http://talkbinary.com/programming/c/recursion-examples/#comments</comments>
		<pubDate>Mon, 29 Mar 2010 05:10:58 +0000</pubDate>
		<dc:creator>Diego</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[C++ recursion examples]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[recursive functions]]></category>

		<guid isPermaLink="false">http://talkbinary.com/?p=2167</guid>
		<description><![CDATA[C++ Recursion Examples Recursion is often one of those topics in programming that many people fail to grasp immediately due to its nature. If you don&#8217;t remember, recursion in C++ is simply a function that calls itself that terminates when a base case is met. But, why can learning this subject be difficult? Since a<a class="moretag" href="http://talkbinary.com/programming/c/recursion-examples/">&#160;&#160;Full Article&#8230;</a>
]]></description>
			<content:encoded><![CDATA[<h2 id="section-1">C++ Recursion Examples</h2>
<p>Recursion is often one of those topics in programming that many people fail to grasp immediately due to its nature. If you don&#8217;t remember, <strong>recursion in C++ is simply a function that calls itself that terminates when a base case is met</strong>.  </p>
<p>But, why can learning this subject be difficult? Since a recursive function may have many and often an unknown amount of recursive calls, its difficult to trace its behavior. The biggest mistake I see when people try to create or traverse these functions, is when they try to do it in their head. If you are a beginner, I recommend you to get rid of this habit and learn to write your ideas down. Trust me, you&#8217;ll save yourself time.</p>
<p><center><img src="http://talkbinary.com/wp-content/uploads/2008/12/fib.jpg"><br />
<small>The recursive calls of Fibonacci when n = 4</small></center></p>
<h2 id="section-2">Getting Started</h2>
<p>Below are a couple of examples to help you learn the process. Before you view them, try working them out on your own. This is always the best way since you&#8217;ll develop a method you&#8217;ll always remember. Only once you gave it your best effort and couldn&#8217;t solve it, go through the examples. Make sure you understand the thought process presented, because once you understand it writing recursive functions should be a lot easier.</p>
<h2 id="section-3">Beginner C++ Recursion Examples</h2>
<p>Below are some basic examples using recursion. These should teach you the basics on base cases, and return statements.</p>
<blockquote><h3 id="section-4">Printing a Sequence of Numbers in Reverse</h3>
<p>By now you should know how to print a sequence of numbers using recursion. What about printing this same sequence in reverse? This should require a minor change to your previous recursive function.</p>
<p><a href="http://talkbinary.com/programming/c/c-recursion-printing-a-sequence-of-numbers-in-reverse/">C++ Recursion &#8211; Printing a sequence of numbers in reverse</a>
</p></blockquote>
<p><span id="more-2167"></span></p>
<blockquote>
<h3 id="section-5">Summation</h3>
<p>Let&#8217;s try doing some math using recursion. Can you create a function that computes the summation of 0, 1, &#8230;, n &#8211; 1, n ? This basic recursive function should help you understand how recursion can be used. </p>
<p>Example:<br />
[pmath]Sum(5) = 5 + 4 + 3 + 2 + 1 = 15[/pmath]</p>
<p><a href="http://talkbinary.com/programming/c/c-recursion-summation/">C++ Recursion &#8211; Summation</a>
</p></blockquote>
<blockquote><h3 id="section-6">Factorial</h3>
<p>Did you understand how the summation function worked using recursion? Try making a function that computes n factorial. </p>
<p>Example:<br />
[pmath]5! = 5 * 4 * 3 * 2 * 1 = 120[/pmath]</p>
<p><a href="http://talkbinary.com/programming/c/c-recursion-factorial/">C++ Recursion &#8211; Factorial</a></p></blockquote>
<h2 id="section-7">Intermediate C++ Recursion Examples</h2>
<p>These intermediate examples require a little bit more thinking since you are dealing with more parameters into your function headers.</p>
<blockquote><h3 id="section-8">Power</h3>
<p>Now that you have a good grip of simple recursive functions, try your hand at something a little bit more difficult.</p>
<p>Example:<br />
[pmath]2^5 = 2 * 2 * 2 * 2 * 2 = 32[/pmath]</p>
<p><a href="http://talkbinary.com/programming/c/c-recursion-power/">C++ Recursion &#8211; Power</a></p></blockquote>
<blockquote><h3 id="section-9">Greatest Common Divisor</h3>
<p>Can you determine the greatest common divisor or two numbers? The example is done using Euler&#8217;s formula. </p>
<p>Example:<br />
[pmath] gcd(12,36) = 12 [/pmath]</p>
<p><a href="http://talkbinary.com/programming/c/c-recursion-greatest-common-divisor/">C++ Greatest Common Divisor</a></p></blockquote>
<blockquote><h3 id="section-10">Logarithm</h3>
<p>Previously we asked you to do a Power function, now something similar. Try doing the logarithm of base 2, and of base n.</p>
<p>Example:<br />
[pmath]2^n = 8, n = 3 [/pmath]</p>
<p>[pmath]4^n = 64, n = 3[/pmath]</p>
<p><a href="http://talkbinary.com/programming/c/c-recursion-logarithm/">C++ Recursion &#8211; Logarithm</a></p></blockquote>
<blockquote><h3 id="section-11">Fibonacci</h3>
<p>Given a definition of a math function, could you come up with a recursive function?</p>
<p>[pmath] Fibonacci(0) = 0 [/pmath]<br />
[pmath] Fibonacci(1) = 1 [/pmath]<br />
[pmath] Fibonacci(n) = Fibonacci(n-1) + Fibonacci(n-2)[/pmath]</p>
<p><a href="http://talkbinary.com/programming/c/c-recursion-fibonacci/">C++ Recursion &#8211; Fibonacci</a></p></blockquote>
<h2 id="section-12">Advanced C++ Recursion Examples</h2>
<p>The following recursive functions are a little more complex since they require a bit more of planning.</p>
<blockquote><h3 id="section-13">Reverse elements of a vector</h3>
<p>Given a vector, can you reverse the order of the elements using recursion?</p>
<p><a href="http://talkbinary.com/programming/c/c-recursion-reverse-elements-of-a-vector/">C++ Recursion &#8211; Reverse elements of a vector</a></p></blockquote>
<blockquote><h3 id="section-14">Determining if a string is a palindrome</h3>
<p>Can you determine if a string is a palindrome? A palindrome is a string that can be read the same both forward and backwards such as <em>racecar</em>, <em>mom</em>, and <em>abba</em>.</p>
<p><a href="http://talkbinary.com/programming/c/c-recursion-palindrome/">C++ Recursion &#8211; Palindrome</a></p></blockquote>
<blockquote><h3 id="section-15">Binary Search</h3>
<p>Can you perform binary search using recursion? </p>
<p><a href="http://talkbinary.com/programming/c/c-recursion-binary-search/">C++ Recursion &#8211; Binary Search</a></p></blockquote>
<h2 id="section-16">Going Further</h2>
<p>Remember, practice makes perfect. Recursion is a difficult subject so don&#8217;t give up early. Just make sure you develop a method to tackle recursion. Once you have one down, recursion shouldn&#8217;t give you trouble. </p>
<p>If you wish to see more examples, post them below. </p>
<ol>
<li>What is faster, an iterative or a recursive version of a function? And why?</li>
<li>Can you do Bubble Sort using recursion?</li>
<li>Can you do Merge Sort?</li>
<li>Is there a way to make Fibonacci require less calls?</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://talkbinary.com/programming/c/recursion-examples/feed/</wfw:commentRss>
		<slash:comments>3</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; 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[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<a class="moretag" href="http://talkbinary.com/programming/c/c-recursion-reverse-elements-of-a-vector/">&#160;&#160;Full Article&#8230;</a>
]]></description>
			<content:encoded><![CDATA[<h2 id="section-1">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 id="section-2">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 id="section-3">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 id="section-4">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 id="section-1">Reversing the elements of a vector using recursion</h2>
<p>So how would we start? What would the function header be?</p>
<blockquote>
<h3 id="section-6">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 id="section-7">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 id="section-8">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 id="section-9">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>
]]></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; 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; 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<a class="moretag" href="http://talkbinary.com/programming/c/c-recursion-fibonacci/">&#160;&#160;Full Article&#8230;</a>
]]></description>
			<content:encoded><![CDATA[<h3 id="section-1">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 id="section-2">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 id="section-3">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
14
15
</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;
&nbsp;
    <span style="color: #666666;">//Our running value</span>
    <span style="color: #0000ff;">int</span> fibn <span style="color: #000080;">=</span> fib1 <span style="color: #000040;">+</span> fib2<span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #666666;">// Computing the nth value of Fibonacci //</span>
    <span style="color: #666666;">// Explained below //</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 id="section-4">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 id="section-3">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 id="section-6">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 id="section-7">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>
]]></content:encoded>
			<wfw:commentRss>http://talkbinary.com/programming/c/c-recursion-fibonacci/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>C++ Recursion &#8211; Printing Elements of a Vector</title>
		<link>http://talkbinary.com/programming/c/c-recursion-printing-elements-of-a-vector/</link>
		<comments>http://talkbinary.com/programming/c/c-recursion-printing-elements-of-a-vector/#comments</comments>
		<pubDate>Sun, 21 Feb 2010 08:05:33 +0000</pubDate>
		<dc:creator>Diego</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[base case]]></category>
		<category><![CDATA[element]]></category>
		<category><![CDATA[helper function]]></category>
		<category><![CDATA[printing function]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[recursive functions]]></category>
		<category><![CDATA[vector]]></category>

		<guid isPermaLink="false">http://talkbinary.com/?p=2169</guid>
		<description><![CDATA[Printing elements of a Vector using Recursion Below is an example of how to print the elements of a vector using recursion. Later, we&#8217;ll print the elements in reverse. Why is this useful? You can apply this principle later to more complex data structures such as Binary Search Trees, or Linked Lists. This tutorial assumes<a class="moretag" href="http://talkbinary.com/programming/c/c-recursion-printing-elements-of-a-vector/">&#160;&#160;Full Article&#8230;</a>
]]></description>
			<content:encoded><![CDATA[<h3 id="section-1">Printing elements of a Vector using Recursion</h3>
<hr />
Below is an example of how to print the elements of a vector using recursion. Later, we&#8217;ll print the elements in reverse. Why is this useful? You can apply this principle later to more complex data structures such as Binary Search Trees, or Linked Lists.<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</a></li>
<li><a href="http://talkbinary.com/programming/c/c-recursion-printing-a-sequence-of-numbers-in-reverse/2/">C++ Recursion &#8211; Printing a Sequence of Numbers in Reverse</a> </li>
</ul>
<h3 id="section-2">Iterative version for printing elements of a vector</h3>
<hr />
To understand how to print elements of a vector using recursion, let&#8217;s write a simple algorithm that will do it for us using iteration.<br />
<br/><br/></p>
<pre lang="c++">
void printVector(vector <int> vec) { 

     for ( int i = 0; i < vec.size(); i++ ) { 

          //Printing ith element  followed by a space
          cout << vec[i] << " ";

     }

     //Printing end line
     cout << endl;
}</pre>
<p><br/><span id="more-2169"></span></p>
<h3 id="section-3">Recursive function for printing elements of a vector</h3>
<hr />
So, how do we go from iteration to recursion? Well if you remember how to <a href="http://talkbinary.com/programming/c/introduction-to-recursion-in-c/">Print a Sequence of Numbers using Recursion</a> without a vector, you know at every recursive call we print an number larger than the previous. In this case we want to print out an element in the vector in increasing order. So what would be our function header?<br />
<br/></p>
<pre lang="c++">void printVector(vector <int> vec) { </pre>
<p><br/><br />
Would this work? Well if you think about it, which element would you print? Using iteration, we used the <b><i>i</b></i> variable to print the <b><i>ith</b></i> element in the vector. Using recursion, we would simply pass this variable, so our function header would be the following.<br />
<br/></p>
<pre lang="c++">void printVector(vector <int> vec, int i) { </pre>
<p><br/><br />
Now, using the knowledge of <a href="http://talkbinary.com/programming/c/introduction-to-recursion-in-c/">Printing a Sequence of Numbers using Recursion</a> we could apply this to printing a sequence of elements in a vector.</p>
<pre lang="c++">void printVector(vector<int> vec, int i) { 

     //Returning when i is larger or equal to the size
    //of the vector
     if ( i >= vec.size() ) {
          return;
     }

     //Printing the ith element of the vector
     cout << vec[i] << " ";

     //Calling the function with a larger i
     printVector(vec, i+1);
}</pre>
<p><br/><br />
Using this function would be done using the following.<br />
<br/></p>
<pre lang="c++">vector <int > vec; 

//Populate vector...

//Calling the printVector function
printVector(vec, 0);</pre>
<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's base case take care of another case where your program might crash? (Hint: What is your function was called with a different i value?)</li>
<li>2. How would you make this function be called by simply passing in the vector and not the element to be printed first (in our example, 0). (Hint: Use <a href="http://talkbinary.com/programming/c/c-helper-functions/">Helper functions</a>)</li>
<li>3. How would you print the elements of the vector in reverse? (Hint: <a href="http://talkbinary.com/programming/c/c-recursion-printing-a-sequence-of-numbers-in-reverse/">Printing a sequence of numbers in reverse</a>)</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://talkbinary.com/programming/c/c-recursion-printing-elements-of-a-vector/feed/</wfw:commentRss>
		<slash:comments>0</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>5</slash:comments>
		</item>
		<item>
		<title>C++ Recursion &#8211; Factorial</title>
		<link>http://talkbinary.com/programming/c/c-recursion-factorial/</link>
		<comments>http://talkbinary.com/programming/c/c-recursion-factorial/#comments</comments>
		<pubDate>Tue, 26 Jan 2010 07:06:33 +0000</pubDate>
		<dc:creator>Diego</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[factorial]]></category>
		<category><![CDATA[function]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[recursive]]></category>
		<category><![CDATA[summation]]></category>

		<guid isPermaLink="false">http://talkbinary.com/?p=2025</guid>
		<description><![CDATA[Creating a factorial function Below is an example of how to calculate the factorial of n. This tutorial expects you to understand the following: C++ Recursion C++ Recursion &#8211; Summation Example: 1 factorial&#40;5&#41;; Result: 1 120 Iterative version of a function that calculates the factorial To understand how to calculate the factorial using recursion, let&#8217;s<a class="moretag" href="http://talkbinary.com/programming/c/c-recursion-factorial/">&#160;&#160;Full Article&#8230;</a>
]]></description>
			<content:encoded><![CDATA[<h3 id="section-1">Creating a factorial function</h3>
<hr />
Below is an example of how to calculate the factorial 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>
</ol>
<p>Example:</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;">factorial<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>

<p>Result:</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: #0000dd;">120</span></pre></td></tr></table></div>

<h3 id="section-2">Iterative version of a function that calculates the factorial</h3>
<hr />
To understand how to calculate the factorial 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
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">int</span> factorial<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;">//Initial value for the final value is 1</span>
     <span style="color: #0000ff;">int</span> factorial <span style="color: #000080;">=</span> <span style="color: #0000dd;">1</span><span style="color: #008080;">;</span>
&nbsp;
     <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;">2</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> 
          factorial <span style="color: #000080;">=</span> factorial <span style="color: #000040;">*</span> n<span style="color: #008080;">;</span>
     <span style="color: #008000;">&#125;</span>
&nbsp;
     <span style="color: #0000ff;">return</span> factorial<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p><span id="more-2025"></span></p>
<h3 id="section-3">Calculating factorial 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> factorial<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> n<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 the factorial for 0, the result should be 1. </p>
<p><br/></p>

<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;">int</span> factorial<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;">//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: #008000;">&#125;</span></pre></td></tr></table></div>

<p><br/></p>
<p>Now, how would we go on by computing the factorial using recursion? Let&#8217;s come up with a formula by calculating the factorial of 2,3, and 4.</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;">factorial<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;
factorial<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> factorial <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;">2</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;
factorial<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> factorial <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;">3</span> <span style="color: #000040;">*</span> <span style="color: #0000dd;">2</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">6</span><span style="color: #008080;">;</span>
&nbsp;
factorial<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">4</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">4</span> <span style="color: #000040;">*</span> factorial <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;">4</span> <span style="color: #000040;">*</span> <span style="color: #0000dd;">6</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">24</span><span style="color: #008080;">;</span> 
&nbsp;
...
&nbsp;
<span style="color: #007788;">factorial</span><span style="color: #008000;">&#40;</span>n<span style="color: #008000;">&#41;</span> <span style="color: #000080;">=</span> n <span style="color: #000040;">*</span> factorial<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></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 factorial formula to any positive integer.<br />
<br/></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">int</span> factorial<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;">//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>
&nbsp;
     <span style="color: #666666;">//factorial(n) = n * factorial(n-1);</span>
     <span style="color: #0000ff;">return</span> n <span style="color: #000040;">*</span> factorial<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: #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>
]]></content:encoded>
			<wfw:commentRss>http://talkbinary.com/programming/c/c-recursion-factorial/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-05-24 09:27:38 -->
