Monday, May 11, 2015

FizzBuzz Part 1




This weekend I started looking at FizzBuzz.  I have to be able to do this in a code interview so I went to Code academy (spelled codecademy) and I'm going through their tutorial.  I will write down what I find helpful so you guys can master the infamous FizzBuzz.  I will assume you found this blog because you know what fizzbuzz is and want to learn how to solve it.  


First thing is to understand a for loop.  The most common way I found it written is:
for (i = 1; i <= 5; i++ )
{
But that didn't help me understand it.  I found a more verbose way to write it.
(//) explains what is happening in each part of the for loop.

Start at 3 count up by 1 and for each number do some code in the brackets { }. // for (start; stop; how much to change each time)
for (var counter = 3; counter <= 5; counter = counter + 1)
{
    // Everything in the code block starting with '{' and
    // ending with '}' will run once each time through the loop
    console.log(counter);
    // console.log will print to the console what you pass inside the ( ).
}
var counter = 3; starts the counter at the number 3.
counter <= 5; go through all the numbers less than(<) or equal(=) to 5.
counter + 1; after you run the code, add 1 to the number and do it again.

So this for loop will start at 3, run the code, console.log the result, then add 1 and run through the for loop again until it gets to a number that is not less than or equal to 5, like 6. When it gets to 6 it will exit out of the for loop.

I had to read this several times and do a few examples of for loops to feel like I understand it completely.  After you understand the for loop, then we tackle the if, else statement below.

if (this condition is true) 
{
    // do this code
}
else
{
    // do this code instead
}

This one was a bit easier to understand.  If (the code in here evaluates to true) {do this code in here} else (if the code evaluates to false) {run this code in here}



So if you think you've got it try this test:

Square the ODD numbers between 1 and 50.
Add an if...else statement to your for loop block that looks at each number. If it is odd, print the square of the number. Otherwise, just print the number.





If you figure that one out try to square the EVEN numbers between 1 and 50. (HINT: %) figure out what % is and how to use it.

I will put the result in this blog article later today.  Don't look for the answer online unless you have spent at least 10 min finding out what % is and trying to write the logic code for odd numbers.

Brought to you by kenyacode, Can you code?

No comments:

Post a Comment