Activity 13-3 - Recursion Versus Iteration



In the previous activity, you tried a program in which a recursive function was used.  Recursion is not absolutely necessary.  In fact, some programming languages do not allow it.  Any task that can be done using recursion can also be done using iteration.  Using iteration, we go through a segment of the main program that is very similar to the recursive function.  Instead of recursion, we will use a loop to go through the code segment as many times as it is required to get to the end.

We will modify the P13_1.cpp program and we use an iterative process instead of recursion.

// P13_2.cpp - This program demonstrates the iterative process
// It takes a string and displays half of it on a line until there is only
// one character left

#include<iostream>
#include<string>
#include<cstring>
#include<cmath>

using namespace std;

int main( )
{
      string my_string;
      int length, count = 1, j;
      string temp;

      cout << "Enter a string \n";
      cin >> my_string;

       length = strlen(my_string.c_str( ))/2;
       temp = my_string.substr(0, length);

       while( length != 1)
       {
             length /= 2;
             count++;
       }

       while( count > 0)
       {

           j = strlen(my_string.c_str( ))/pow(2,count);
           temp = my_string.substr(0, j);
           cout << temp << endl;
           count--;
       }
       return 0;
}

This program produces the same results as the one given in the previous activity but uses an iterative process instead of recursive process.  As you may have noticed, in this program we also have a stopping case.  To reach the base case, we used a counter to stop the iteration when the necessary number of iterations are made.
 

Exercise 13.3
Write the program that computes the factorial of a number using an iterative process.
            n! = n(n-1)(n-2)(n-3)...(2)(1)