title: Optmizing functions
body: <p>There is a section of the book I am using to learn c++ which teaches about optimizing functions. </p>
  
  <p>The code is as follows:</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  using namespace std;
  
  int computeFactorials(int, int);
  
  int factorial(int);
  
  int main() {
      computeFactorials(1, 5);
      return 0;
  }
  
  int computeFactorials(int num, int max) {
      cout &lt;&lt; "Factorial of " &lt;&lt; num &lt;&lt; ": ";
      cout &lt;&lt; factorial(num) &lt;&lt; endl;
      num++;
      if(num &gt; max)
          return 0;
      else
          computeFactorials(num, max);
  }
  
  int factorial(int n) {
      int result;
      if (n == 1)
           result = 1;
      else
           result = (factorial(n-1) * n);
      return result;
  }
  </code></pre>
  
  <p>Here is the program execution:</p>
  
  <pre><code>Factorial of 10: 3628800
  
  C:\MyPrograms\c++ optimize.cpp -o optimize.exe
  
  C:\MyPrograms&gt;optimize
  Factorial of 1: 1
  Factorial of 2: 2
  Factorial of 3: 6
  Factorial of 4: 24
  Factorial of 5: 120
  </code></pre>
  
  <p>I can follow up to num == 3, but when it gets to 4 my logic doesn't add up with the results.  I am reading the code like this:</p>
  
  <p><code>computeFactorials(1,5)</code>, 1 meaning the number to start at, and 5 meaning the maximum number of loops. I'm going to start at 3 per se because I understand 1 and 2 as num. </p>
  
  <p>"Factorial of " (3) : <code>factorial(3)</code>, then in the factorial function 3 is subtracted by 1 equaling 2, and then multiplied by 3 for a result of 6.</p>
  
  <p>However, when the program gets to num equaling 4 this doesn't seem to make any sense anymore.  Because the int result of the factorials() functions should equal 12 not 24. </p>
  
  <pre><code>else result = (factorials (4-1) * 4) ; 
  </code></pre>
  
  <p>3 * 4 = 12, not 24. How is this program getting to 24 and not 12? Then once again doing the same thing on num = 5, getting 120 rather than 20.</p>
  
  <p>Please help me understand, I am still very nooby in this language, thank you. :)</p>