I’m fairly new to programming and am avidly trying to learn R. I am attempting to solve the classic “Fizzbuzz” problem in R and have almost figured out a way, but my loop is printing twice. Tried debugging and searching, but I can’t seem to find anything. Any suggestions?
tl;dr Do you know why this for loop prints twice?
fizzbuzz = function(n){
if ( n %% 15 == 0 ) {
print("Fizzbuzz")
} else
if ( n %% 5 == 0 ) {
print("buzz")
} else
if ( n %% 3 == 0 ) {
print("Fizz")
} else {
print(n)
}
}
for (a in 1:100)
print(fizzbuzz(a))
Because you call
printtwice, once in the function and once in the loop. Remove theprintin the loop and it only prints once.