Loop Exercises in Programming in Objective-C

In addition to my traditional posts, I want to use this website as a personal journal recording my experiences learning to code. This is the first of what will be many posts relating to my learning. The main purpose of these posts are for my own benefit, processing my own thoughts by writing them down and keeping them for posterity. If you skip it, I won’t be sad.

I’m continuing to march towards my goal of learning to program iPhone apps. Rather than stumbling blindly forward, as I have in my past attempts, I am now aided by the help of two friends and iOS developers: Will, a coder at a New York based startup and Massimo of iRealB. I’m finding that meeting with people, in person, and discussing code is helping me immensely with my motivation and progress.

Both of my friends recommended Programming in Objective-C by Stephen Kochan, a book that I hadn’t explored before. Programming in Objective-C is different from most of the other programming books I’ve attempted thus far, as Stephen doesn’t assume the reader is already familiar with another programming language. This had always been my main struggle: finding a programming book that doesn’t assume any prior knowledge.

I do find that my experiences with Codecademy and halfway progress through the Rails Tutorial have greatly enhanced my understanding of the Objective-C language, but Programming in Objective-C is the first book where I just get it. Whether this is a result of experience or simply a different presentation of the material, I can’t say for sure.

My learning process so far has been this: meet with Massimo and look at the topic of the next chapter in the book. Then, we’ll code together (mostly, he’ll tell me what to code) writing made-up examples within that particular chapter topic. For the chapter on classes, we made a few basic classes. The chapter on expressions, we both play around with expressions in Objective-C. Then, I’d use the rest of the week to actually read the chapter on my own, making sure I understand everything before moving forward, and performing the exercises in at the end of the chapter on my own.

I’ve just completed chapter 5: “Programming Loops,” and stumbled upon my first example that really made me struggle.

The factorial of an integer n, written n!, is the product of the consecutive integers 1 through n. For example, 5 factorial is calculated as follows:
      5! = 5 x 4 x 3 x 2 x 1 = 120
Write a program to generate and print a table of the first 10 factorials.

My brain’s first response, as reading this questions, was to go completely blank. I knew the answer would involve loops (not only was that the topic of this chapter, but that part is already obvious to me). I just had to figure out how to put the loop together.

I knew that I would need to utilize both subtraction and multiplication, as I needed to take a number i, subtract 1, multiply that by the original number, subtract 1 again, multiply that, and so on until i became 1.

The initial challenge, when tackling these logic problems, is knowing how many variables to declare and what I’ll do with each. I’d need an integer for my loop (I’m a fan of using i, although the book usually uses n) as well as at least one more integer variable to store the sum of the multiplication as my program going through the loop.

The question asked for a table with the first 10 factorials, which I interpreted as a table with two columns, the first listing the numbers from 1 to 10 and the second listing the corresponding factorials.

Since I’d need to calculate factorials for each of the integers between 1 and 10, I knew I’d need a loop that would calculate each integer between 1 and 10, one by one. To do this, I’d need a loop. Then I’d need another loop inside that loop to calculate the factorial for each integer.

I started easy:

for (int i = 1; i <= 10; i++)

Now I needed to figure out what went inside this loop.

I knew that i would be the number that I would need to work with, so I initially used the integer of i within the loop, creating a process where I subtracted 1 and then *= that number to i. But a bit of critical thinking, and an unsuccessful build and run later, I realized that messing with i messed with the loop. Since the loop is performing it’s task and handling the i++ feature, messing with i can result in exiting the loop early or other unexpected results.

I created a new integer, that I called temp (horrible naming convention, but I had no idea what to call it yet because I was just testing out ideas) that I could assign the value of i.

I’d need to assign the value of i to my integer temp, subtract one, multiply that number by the original temp value, save that new value, and continue. I just started writing equations, testing ideas out. I wrote a for loop inside the above for loop, added an NSLog command to print out numbers as my program looped through the code, but for some reason the loop only processed my number once, returned one value, then exited.

Much of my confusion stemmed from the loop within a loop, so I decided to ditch the 10 to 1 countdown loop and instead isolate the factorial number loop. Once I got that to work, I’d insert it into my previous loop.

I decided I wanted to test my new loop by calculating the factorial number of 5, since that’s smack dab in the middle of 1 and 10. I assigned 5 to an int variable outside the loop, then used that variable in a loop.

int factorialNumber = 1;
int number = 5;

for (int i = number; i > 0; i--)

This was my first time working with decreasing loops (i-- rather than i++) but since I’d be subtracting 1 from the number until it equaled 1 (multiplying the number by 0 would obviously mess things up).

At the end of this loop, I knew that I’d need the factorial number of whatever was assigned to number. My original plan was to subtract 1 from my int number in the first line of the loop, but I realized I could have the loop do that for me. All I’d need in my loop was factorialNumber *= i (by this point, I had renamed temp to factorialNumber).

After a bit of condensing, here’s what I had (and changing my counter integer to j, since I wanted to use i in my initial loop):

int factorialNumber = 1;

for (int j = 5; j > 0; j--) {
      factorialNumber *= j;
}

NSLog(@"Factorial Number is: %i",factorialNumber);

This returns the factorial number for 5, and I can change the number 5 in the loop to anything I want. Next, I needed to figure out how to put this loop into my other loop.

I realized that I would be calculating the factorial for each number, from 1 – 10, which is what the value of i is going to be in the first loop. By subsituting “5” in the second loop with i, I’d be able to process each number and get the results I want.

After playing around a bit, getting things just right, here was my final code:

for (int i = 1; i <= 10; i++) {
      int factorialNumber = 1;
      for (int j = i; j > 0; j--) {
         factorialNumber *= j;
      }
      NSLog(@"i: %2i, temp: %i", i, factorialNumber);
}

The process of arriving at this final code took a lot of thinking and a few walks around the block. But I ended up with the code I needed, doing exactly what I wanted it to do. There were a few times that I wanted to just give up and ask for help, but I stuck it out and ended up getting the answer.

I can’t wait for problems like these to become second nature so I can start tackling more complex exercises.

Related Posts: