Monday, May 11, 2015

FizzBuzz Part 2

In my last blog I set out a challenge: Can you write a for loop with an if else statement. If you haven't read the last post, go now and then come back here for the answer.

The challenge is to Square just the ODD numbers between 1 and 50, and print each number in the console.

In order to accomplish this feat, you need a for loop that counts all numbers between 1 and 50. If the number is odd, print the square of the number. Otherwise, just print the number. Here is the solution.

for (var i=1; i <= 50; i++)
     {
     if (i % 2 == 1)
         console.log(i * i);
     else
         console.log(i);
     }

If you figured this out then it means you know that % is a modulo. An operator that gives you the remainder when two numbers are divided together and the remainder is only in whole numbers. So if i=1, there is a remainder of one but if you square 1 you get 1. If i=2, no remainder and if i=3, remainder of 1 and the square is 9, etc.

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.

for (var i=1; i <= 50; i++)
     {
     if (i % 2 == 0)
         console.log(i * i);
     else
         console.log(i);
     }

Did you see the change? Keep looking

Ok, in line 3 if you set the remainder equal to 0 then the if statement will evaluate to true only for the even numbers.

To square the result I used i * i or i x i.

Hope you see where this is going. My next blog will get even closer to understanding and passing FizzBuzz. For the next challenge, try to start your counter at 10 and count down to 0, when you get to 0 console.log Blast Off!.


Special note: I did get hung up on the for loop because I was thinking Ruby and did not put the if else statement inside the { }

Brought to you by KENYACODE. Can you code?

No comments:

Post a Comment