"for" loop from program 7.6 from Kochan's "Programming in Objective-C"
- by Mr_Vlasov
"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."
#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", &n);
pow2 = 2;
for (i = 1; i <= 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;
}
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? :
sum2 = [sum add: aFraction];
[sum release]; // release previous sum
sum = sum2;
Is it just for the sake of avoiding memory leakage? (method "add" initializes a variable that is stored in sum2)