Tuesday, May 22, 2012

Interesting Article and My Solution

So, I found an article on Coding Horror about how most programmers can actually not write a simple program. I figured their example question that people have trouble writing would be a good test to see how efficient I could make it.

The problem is as follows:

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 started at (4:33:35 AM) and ended at (4:36:45 AM) for a total of around 3 minutes and 10 seconds.

Here is what I came up with:

#include <stdio.h>

int main()
{
     /* 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". */

     for (int num = 1; num <= 100; num++)
     {
          if (num % 3 == 0)
             printf ("Fizz");
          if (num % 5 == 0)
             printf ("Buzz");
  
          if ((num % 3 != 0) && (num % 5 != 0))
             printf ("%d", num);
  
          printf ("\n");
     }

     return 0;
}

The short article is a fantastic read and only takes a second. Both solutions that appear early in the comments fail for various reasons. It is not necessary to have a statement to print both Fizz and Buzz when you can simply leave out the newline until the end and solve both in one go.

Even though it's simple problem and may seem like a step back in complexity from the previous post I'm happy with my solution. Moving to something a bit more complex tomorrow. For now, I need sleep.

No comments:

Post a Comment