Writing Fizz Buzz in Xcode

Fizz Buzz is a common programming challenge that I’ve seen referenced numerous times since first learning about it through Codecademy. The prompt is this:

Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz.”

I remember stumbling my way through the Codecademy lesson, not really understanding it but going through the motions. Since that day (back in January, I believe it was) I had completely forgotten the details of the question and the approach for solution.

Yesterday, however, I was thinking about programming challenges and my progress thus far and remembered the Fizz Buzz challenge. I decided I’d Google the details and give it a shot in Xcode1. I was able to create some working code in less than five minutes(!) and so I figured I’d share my work process with my code journal.

I’ve realized that part of learning to code is learning to break problems into tiny little pieces. When I first started, I’d want to tackle everything that once; I’d be stuck on the first line of code since I didn’t want to solve one part then have to change everything when I needed to add another part. The largest aspect of learning to code, for me, was realizing that code really does build on other code, and 99% of the time you’ll simply be able to add to existing code to create new features. The other 1%, where the code needs to be completely rewritten, is still an extremely valuable way to think about the problem.

I know this often gets repeated ad nauseum, but just start writing the code.

So, the first component of Fizz Buzz is to print the numbers from 1 to 100. Before we can even worry about multiples of three or five, we need to create a program that simply prints out 1 through 100. That’s easy, we just need a simple loop.

for (int i = 1; i <= 100; i++) {
     NSLog(@"%i", i);
}

That’s it. Run that snippet of code and you’ll get each number between 1 and 100 printed to the console. Fantastic.

Now, it’s time to add our first exception to the rule, printing Fizz instead of each multiple of three. Another way to think about this word-replacement is: if the number is a multiple of three, print Fizz, otherwise print the number. This construct is an if/else statement.

An if/else statement is exactly what I used. Since “print the number without any modifications” is the default action if it’s not a multiple of three, that bit of code will be part of the catch-all “else” code. The calculations for multiples of three will be part of the if statement.

So how can we tell if a number is a multiple of three? My brain first snapped to an extremely complicated solution: take 3 * 1, then check that against i, then 3 * 2 calculated against i, and so on. For this, I’d need a whole new loop, and I’d need to create a way to break that loop eventually, meaning I’d need to enter j < ?? perimeter, which means the code wouldn’t be scalable.

Luckily, we have the modulo operator (%). This bit of code divides the first number by the second number and returns the remainder of the result. So:

100 % 4 = 0

Going back to Fizz Buzz, multiples aren’t just solvable through multiplication. Sure, 26 * 3 is guaranteed to be a multiple of three. This also means that if a number is evenly divided by three, it’s also a multiple of three.

100 % 3 = 1 (100 is not a multiple of three)

99 % 3 = 0 (99 is a multiple of three)

Let’s head back to the loop we already wrote and add a test for multiples of three.

for (int i = 1; i <= 100; i++) {
     if (i % 3 == 0) {
          NSLog(@"Fizz");
     }
     else {
          NSLog(@"%i", i);
     }
}

If we run that code, we’ll see that every multiple of three has been replaced with the word “Fizz.” We’ll find and replace multiples of five the same way, this time with an else if statement and with the word “Buzz.”

for (int i = 1; i <= 100; i++) {
     if (i % 3 == 0) {
          NSLog(@"Fizz");
     }
     else if (i % 5 == 0) {
          NSLog(@"Buzz")
     }
     else {
          NSLog(@"%i", i);
     }
}

Running this code replaces multiples of three and multiples of five. The only think left to add is the word FizzBuzz to each number that is divisible by both three and five.

If we look at our console log, we’ll see that numbers divisible by both three and five are currently printing “Fizz.” This is because our if statement for “Fizz” comes before our statement to print “Buzz.” So even though these numbers are divisible by both three and five, the program is satisfied after the first if statement and that cycle through the loop is complete, without the “else if” statement even being checked.

If we add our FizzBuzz statement after the current if or else if statement, it’ll never be read because the loop will be satisfied before we even get to the FizzBuzz test. We’ll need to add this to the very beginning, like such:

for (int i = 1; i <= 100; i++) {
     if (i % 3 == 0 && i % 5 == 0) {
          NSLog(@"FizzBuzz")
     }
     else if (i % 3 == 0) {
          NSLog(@"Fizz");
     }
     else if (i % 5 == 0) {
          NSLog(@"Buzz")
     }
     else {
          NSLog(@"%i", i);
     }
}

Since the FizzBuzz test is now our first if statement, we have to change the Fizz test to an else if statement.

That’s it. This program matches all the perimeters of the Fizz Buzz challenge. You just have to build it piece by piece. Fizz. Buzz.

  1. Since I’m learning Objective-C without a background in C, I’m still mostly unclear as to the differences. As a result, I’m not sure if the code I wrote qualified as Objective-C or could just be considered plain C. I know that it doesn’t really matter, since Xcode compiles both Objective-C and C, but I figured I’d write “give it a shot in Xcode” as to avoid referring to the programming language incorrectly.

Living in Computers and Other Crotch Shots

Ben Makuch writing for Vice.com:

According to Moore’s Law, which states that computing power doubles roughly every two years, all of this will be theoretically possible in the future. Sooner or later, we’ll get to a place where simulating a few billion people—and making them believe they are sentient beings with the ability to control their own destinies—will be as easy as sending a stranger a picture of your genitals on your phone.

I’ve always found this theory fascinating, although I don’t personally subscribe to these beliefs. I don’t have any information to refute the idea that we’re all computer simulations in some large “video game,” but I just have a gut feeling. Like, you know when it’s the middle of the night and you’re stumbling to the bathroom, and you’re saying “I’m gonna step on something, I’m going to step on something,” over and over again, but you never actually step on something. If, however, you’re thoughtlessly head to the bathroom in the dark, you’ll no doubt step on something? It’s kinda like that.

Anecdotally, the fact that we’re thinking about this theory in the first place decreases its likelihood.

Alright, time to get back to writing loops.

Google Glasses as Couture Fashion

Diane Von Furstenberg put her models in the Google Glasses Explorer Edition for her Spring 2013 show at Fashion Week. Here’s Lauren Indvik reporting for Mashable:

The bands of each pair [of Google Glasses] were modified to complement the collection’s palette of corals, blues, whites and grays. It was the first time Glass had ever appeared on a runway.

This is a big deal. While runway fashion often displays over-the-top garb and impractical styles, everything that happens on the runway does make it to the streets in one form or another. Outlets such as H&M and Forever 21 are nothing but runway-diffusion machines, taking impractical/exorbitantly priced fashion and making the styles street-appropriate and affordable.

Putting models in Google’s glasses, and pulling Sergey Brin on stage at the end, is a huge win for Google. It’s one thing if self-proclaimed computer geeks and nerds wear Google Glasses, it’s another to see them on models. Google is really doing all they can to make these a fashion statement. And they just took one giant step forward.

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.

App.net is Not the Answer, and Why I Gave Them Money

I do not think App.net is the answer.

I do believe Dalton’s views on the detrimental nature of ad-supported services is spot-on. There are, however, fatal flaws with customer supported services, too.

People do not want to pay for digital services or goods. It’s been like this since the invent of the Internet. Thanks to Apple, some people are willing to pay a small one-time fee which include a lifetime of unlimited updates, which is about as close to free as a paid-model can get.

While pay-for-a-service is sustainable, it doesn’t support the viral and sustainable growth and adoption. Case study: Hipstamatic vs Instagram.

Somewhere in the middle, between ad-supported and paid, is the answer. It’s a goldmine, and it’s still waiting to be discovered.

We’re getting closer. The funding of App.net shows that we’re1 willing to depart from the current unsustainable ad-supported startup trend.

That is what I want to support.

  1. Well, at least some of us. Others are just gamblers, hoping for the coveted “early adopter” badge of pride.

Cyborgs, Biohacking, and Magnetic Implants

Ben Popper, writing for The Verge:

People passing by gave us odd stares as Berg and I stood next to each other in the street, waving our hands around inside an invisible field, like mystics groping blindly for a ghost.

Fantastic article about the current state of biohacking. And I helped.