< Browse > Home / Archive by category 'Programming / C++'

C++ Recursion – Logarithm

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 assumes you understand C++ Recursion and the C++ Recursion – Power function.

Example of finding the logarithm given a base

You could find the base using two different methods.

  1. Multiply the base by itself until you receive the number.
  2. 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.

logBase2(8) = 3
2 * 2 * 2 = 8

Method 2:
8/2 = 4
4/2 = 2
2/2 = 1

logBaseN(16,2) = 4
2 * 2 * 2 * 2 = 16

Method 2:
16/2 = 8
8/2 = 4
4/2 = 2
2/2 = 1

Recursive version of logBase2 function

Given the example above, could you come up with a logBase2 recursive function? Let’s try using the 2nd method described above. So what would be our base case and header?
Read more »

[ More ] March 14th, 2010 | No Comments | Posted in C++, Functions by Diego |

C++ Recursion – Palindrome

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.

C++ Recursion

Example of finding if a word is a palindrome

To determine if a word is a palindrome do the following.

  1. Compare the first and last character
  2. If these characters are the same, disregard these characters and repeat until one one character or no characters remain

Example:

// 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.
 

Now let’s try one that isn’t a palindrome.

// First iteration
[ t ] [ a ] [ b ] [ t ]

// In our second iteration, a and b don’t match
[ a ] [ b ]

Read more »

[ More ] March 10th, 2010 | No Comments | Posted in C++, Functions by Diego |

C++ Recursion – Reverse elements of a vector

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 by simply intuition.

// 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 ]
 

Notice how once we arrive at the entry in the middle of the vector we don’t continue. Why? The values beyond this entry have already been swapped. Keep this in mind.

Reversing the elements of a vector using iteration

Before we try making a recursive function to reverse the elements of a vector, let’s make one using iteration. By following the method described in the method above, it’s easy to see that we are simply swapping the ith and (nth – ith) variables (Example: the 0th and the 4th (4th – 0th) element).

Reversing the elements of a vector using iteration

The iterative solution for reversing the elements of a vector is below. Make sure you are trying all these functions if you haven’t before on your own.

//We pass the vector by reference
void reverseElements(vector <int> &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;
}

Make sure you understand this completely before moving forward. Try working it out by hand.

Read more »

[ More ] March 8th, 2010 | No Comments | Posted in C++, Functions by Diego |

C++ Recursion – Greatest Common Divisor

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.

Euclid’s Algorithm

When studying computer science a famous algorithm taught to students is the Euclidean Algorithm which is used to compute the greatest common divisor of two integers. It’s definition is below.

gcd(x,y)

Computing various examples


So how does it work? Well, let’s follow the definition, but before doing that, do you remember how to compute the remainder of two integers in c++? If you don’t, well it’s the % (mod) operator.

// Computing the gcd of 45 and 9 //
gcd(45, 9)
= gcd(9, 45 % 9 ) = gcd(9, 0)
= 9

// Computing the gcd of 54 and 12 //
gcd(54, 12)
= gcd(12, 54 % 12) = gcc(12, 6)
= gcd(6, 12 % 6) = gcd(6, 0)
= 6

Read more »

[ More ] March 7th, 2010 | No Comments | Posted in C++, Functions by Diego |

C++ Recursion – Fibonacci

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:

Fibonacci is a well known number sequence that models the growth of a rabbit population amongst other things found in nature.

Below is the Fibonacci numbers computed up to the 11th term.

0 1 2 3 4 5 6 7 8 9 10 11
0 1 1 2 3 5 8 13 21 34 55 89

Iterative version of Fibonacci


Before we create the recursive version of Fibonacci, let’s look at how to create the iterative version by looking at the formula.

Fibonacci Formula

Fibonacci(0) = 0;
Fibonacci(1) = 1;
Fibonacci(n) = Fibonacci(n-1) + Fibonacci(n-2);

So how would we do an iterative version? I’ll walk you through the code.

// The value of n is the Fibonacci number we want to compute //
int fibonacci(int n) {

    //Our two initial values
    int fib1 = 0;
    int fib2 = 1;

    //Our running value
    int fib = fib1;

    // Computing the nth value of Fibonacci //

   return fib;
 

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’d do it as following:
Read more »

[ More ] February 23rd, 2010 | No Comments | Posted in C++ by Diego |

C++ Recursion – Printing Elements of a Vector

Printing elements of a Vector using Recursion


Below is an example of how to print the elements of a vector using recursion. Later, we’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 you understand the following:

Iterative version for printing elements of a vector


To understand how to print elements of a vector using recursion, let’s write a simple algorithm that will do it for us using iteration.

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;
}

Read more »

[ More ] February 21st, 2010 | No Comments | Posted in C++ by Diego |

C++ Recursion – Power Continued

Creating a power function using Recursion


So, previously we tried computing the Power function using recursion but we didn’t take into account when the exponent was negative. This continues the previous function, so if you haven’t yet, go back. Make sure you understand the following as well:

  1. C++ Recursion
  2. C++ Recursion – Summation
  3. C++ Recursion – Factorial

Power Function using Recursion


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?

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;

}

Let’s start by coming up with a formula again.

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);

Taking into account negative exponents


So now that we have a formula, what would be our base case? We surely don’t want our previous base case to return 1 when (n==0) because that would be wrong.
Read more »

[ More ] February 11th, 2010 | No Comments | Posted in C++ by Diego |
Page 1 of 612345...Last »