# Fizz Buzz Interview Test in R

Apparently a common programming interview test is to have the candidate write a program that meets the following requirements:

• Print the numbers from 1 to 100
• When the number is a multiple of 3 print “Fizz” instead of the number
• When the number is a multiple of 5 print “Buzz instead of the number
• When the number is a multiple of both print “FizzBuzz”

I thought it would be fun to try this in R. My solution to the Fizz Buzz interview test in R is below. You can also see this code in my GitHub.

## Create a Loop that Prints the Numbers from 1 to 100

Although some say to avoid loops in R in this case a loop seems like a good way to solve this problem. First let’s make a loop that just prints the numbers from 1 to 100:

```# Print the numbers from 1 to 100

for (i in 1:100) {
print(i)
}

```

This produces the following (output cut off at 15 to save space):

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15

## Have R Print “Fizz” for Multiples of 3

Now let’s add an if else statement that prints “Fizz” for multiples of three. Note that this solution uses the modulo command which calculates the remainder. In this case the value of i is divided by three and the remainder is produced:

```# Print the numbers from 1 to 100
# For multiples of 3 print "Fizz"
i <- 1
for (i in 1:100) {
if(i %% 3 == 0) {print("Fizz")}
else print(i)
}```

This produces the following (output cut off at 15 to save space):

 1
 2
 “Fizz”
 4
 5
 “Fizz”
 7
 8
 “Fizz”
 10
 11
 “Fizz”
 13
 14
 “Fizz”

## Have R Print “Fizz” for Multiples of 3 and “Buzz” for Multiples of 5

Now we’ll add and else if command to tell R to print “Buzz” for multiples of five. Note that values of i that are multiples of both will print “Fizz” because that is the first command:

```# Print the numbers from 1 to 100
# For multiples of 3 print "Fizz"
# For multiples of 5 print "Buzz"

for (i in 1:100) {
if (i %% 3 == 0) {print("Fizz")}
else if (i %% 5 == 0) {print("Buzz")}
else print(i)
}```

This produces the following (output cut off at 15 to save space):

 1
 2
 “Fizz”
 4
 “Buzz”
 “Fizz”
 7
 8
 “Fizz”
 “Buzz”
 11
 “Fizz”
 13
 14
 “Fizz”

## Have R Print “FizzBuzz” for Numbers that are Multiples of Both 3 and 5

Finally we’ll add a command at the beginning that tells R to print “FizzBuzz” for multiples of both 3 and 5:

```# Print the numbers from 1 to 100
# For multiples of 3 print "Fizz"
# For multiples of 5 print "Buzz"
# For multiples of both print "FizzBuzz"

for (i in 1:100) {
if (i %% 3 == 0 & i %% 5 == 0) {print("FizzBuzz")}
else if (i %% 3 == 0) {print("Fizz")}
else if (i %% 5 == 0) {print("Buzz")}
else print(i)
}```

This produces the following (output cut off at 15 to save space):

 1
 2
 “Fizz”
 4
 “Buzz”
 “Fizz”
 7
 8
 “Fizz”
 “Buzz”
 11
 “Fizz”
 13
 14
 “FizzBuzz”

If you’re interested in doing this “the R way” without a loop there is a vectorized solution here: http://librestats.com/2012/01/10/honing-your-r-skills-for-job-interviews/