I tried so hard to complicate this and in the end it took me close to 3 hours to figure out. I was trying to start the
factorial from 0 each time and add 1 until it reached the
number variable. This became very complicated. It only became apparent quite late on that actually the result for the previous
factorial was cumulative and therefore could be used again.
// Chapter 5 - Program Looping - Exercise 3
// Program that generates a table of the first 10 factorials
int main (int argc, char *argv [])
{
int number, factorial;
NSLog (@"Number Factorial");
NSLog (@"------ ---------");
for (number = 1, factorial = 1; number <= 10; number++) {
factorial = factorial * number;
NSLog(@"%2i %i",number,factorial);
}
return 0;
}
Output:
2011-12-29 21:09:35.479 exercises[2211:707] Number Factorial
2011-12-29 21:09:35.481 exercises[2211:707] ------ ---------
2011-12-29 21:09:35.482 exercises[2211:707] 1 1
2011-12-29 21:09:35.483 exercises[2211:707] 2 2
2011-12-29 21:09:35.483 exercises[2211:707] 3 6
2011-12-29 21:09:35.484 exercises[2211:707] 4 24
2011-12-29 21:09:35.484 exercises[2211:707] 5 120
2011-12-29 21:09:35.485 exercises[2211:707] 6 720
2011-12-29 21:09:35.486 exercises[2211:707] 7 5040
2011-12-29 21:09:35.486 exercises[2211:707] 8 40320
2011-12-29 21:09:35.487 exercises[2211:707] 9 362880
2011-12-29 21:09:35.487 exercises[2211:707] 10 3628800