title: "for" loop from program 7.6 from Kochan's "Programming in Objective-C"
body: <p>"The sigma notation is shorthand for a summation. Its use here means to add the values
  of 1/2^i, where i varies from 1 to n. That is, add 1/2 + 1/4 + 1/8 .... If you make the
  value of n large enough, the sum of this series should approach 1. Let’s experiment with
  different values for n to see how close we get."</p>
  
  <pre><code>#import &lt;Foundation/Foundation.h&gt;
  // Define the Fraction class
  @interface Fraction : NSObject
  {
  int numerator;
  int denominator;
  }
  @property int numerator, denominator;
  -(void) print;
  -(void) setTo: (int) n over: (int) d;
  -(Fraction*) add: (Fraction *) f;
  -(void) reduce;
  @end    
  
  #import "Fraction.h"
  @implementation Fraction
  @synthesize numerator, denominator;
  -(void) print
  {
  NSLog (@"%i/%i", numerator, denominator);
  }
  -(void) setTo: (int) n over: (int) d
  {
  numerator = n;
  denominator = d;
  }
  -(Fraction *) add: (Fraction *) f
  {
  // To add two fractions:
  // a/b + c/d = ((a*d) + (b*c)) / (b * d)
  // result will store the result of the addition
  Fraction *result = [[Fraction alloc] init];
  result.numerator = numerator * f.denominator +
  denominator * f.numerator;
  result.denominator = denominator * f.denominator;
  [result reduce];
  return result; 
  }
  
  #import "Fraction.h"
  int main (int argc, char *argv[])
  {
  NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  Fraction *aFraction = [[Fraction alloc] init];
  Fraction *sum = [[Fraction alloc] init], *sum2;
  int i, n, pow2;
  [sum setTo: 0 over: 1]; // set 1st fraction to 0
  NSLog (@"Enter your value for n:");
  scanf ("%i", &amp;n);
  pow2 = 2;
  
  for (i = 1; i &lt;= n; ++i) {
  [aFraction setTo: 1 over: pow2];
  sum2 = [sum add: aFraction];
  [sum release]; // release previous sum
  sum = sum2;
  pow2 *= 2;
  }
  
  NSLog (@"After %i iterations, the sum is %g", n, [sum convertToNum]);
  [aFraction release];
  [sum release];
  [pool drain];
  return 0;
  }
  </code></pre>
  
  <p>Question: Why do we have to create additional variable sum2 that we are using in the "for" loop? Why do we need  "release previous sum" here and then again give it a value that we just released? :</p>
  
  <pre><code>sum2 = [sum add: aFraction];
  [sum release]; // release previous sum
  sum = sum2;
  </code></pre>
  
  <p>Is it just for the sake of avoiding memory leakage? (method "add" initializes a variable that is stored in sum2)</p>