FizzBuzz in R: Print Numbers with Fizz, Buzz, and FizzBuzz
Write a R program to print the numbers from 1 to 100 and print "Fizz" for multiples of 3, print "Buzz" for multiples of 5, and print "FizzBuzz" for multiples of both.
Sample Solution :
R Programming Code :
# Loop through numbers from 1 to 100
for (n in 1:100) {
# Check if 'n' is divisible by both 3 and 5
if (n %% 3 == 0 & n %% 5 == 0) {
# Print "FizzBuzz" if divisible by both
print("FizzBuzz")
}
# Check if 'n' is divisible by 3 only
else if (n %% 3 == 0) {
# Print "Fizz" if divisible by 3
print("Fizz")
}
# Check if 'n' is divisible by 5 only
else if (n %% 5 == 0) {
# Print "Buzz" if divisible by 5
print("Buzz")
}
# If 'n' is neither divisible by 3 nor 5
else {
# Print the number 'n'
print(n)
}
}
Output:
[1] 1 [1] 2 [1] "Fizz" [1] 4 [1] "Buzz" [1] "Fizz" [1] 7 [1] 8 [1] "Fizz" [1] "Buzz" [1] 11 [1] "Fizz" [1] 13 [1] 14 [1] "FizzBuzz" [1] 16 [1] 17 [1] "Fizz" [1] 19 [1] "Buzz" [1] "Fizz" [1] 22 [1] 23 [1] "Fizz" [1] "Buzz" [1] 26 [1] "Fizz" [1] 28 [1] 29 [1] "FizzBuzz" [1] 31 [1] 32 [1] "Fizz" [1] 34 [1] "Buzz" [1] "Fizz" [1] 37 [1] 38 [1] "Fizz" [1] "Buzz" [1] 41 [1] "Fizz" [1] 43 [1] 44 [1] "FizzBuzz" [1] 46 [1] 47 [1] "Fizz" [1] 49 [1] "Buzz" [1] "Fizz" [1] 52 [1] 53 [1] "Fizz" [1] "Buzz" [1] 56 [1] "Fizz" [1] 58 [1] 59 [1] "FizzBuzz" [1] 61 [1] 62 [1] "Fizz" [1] 64 [1] "Buzz" [1] "Fizz" [1] 67 [1] 68 [1] "Fizz" [1] "Buzz" [1] 71 [1] "Fizz" [1] 73 [1] 74 [1] "FizzBuzz" [1] 76 [1] 77 [1] "Fizz" [1] 79 [1] "Buzz" [1] "Fizz" [1] 82 [1] 83 [1] "Fizz" [1] "Buzz" [1] 86 [1] "Fizz" [1] 88 [1] 89 [1] "FizzBuzz" [1] 91 [1] 92 [1] "Fizz" [1] 94 [1] "Buzz" [1] "Fizz" [1] 97 [1] 98 [1] "Fizz" [1] "Buzz"
Explanation:
- Loop Through Numbers: for (n in 1:100) iterates over each number n from 1 to 100.
- Check Divisibility by 3 and 5: if (n %% 3 == 0 & n %% 5 == 0) checks if n is divisible by both 3 and 5.
- Print "FizzBuzz": If true, it prints "FizzBuzz".
- Check Divisibility by 3: else if (n %% 3 == 0) checks if n is divisible by 3 but not 5.
- Print "Fizz": If true, it prints "Fizz".
- Check Divisibility by 5: else if (n %% 5 == 0) checks if n is divisible by 5 but not 3.
- Print "Buzz": If true, it prints "Buzz".
- Print the Number: else print(n) prints the number n if none of the above conditions are met.
Go to:
PREV : Write a R program to get all prime numbers up to a given number (based on the sieve of Eratosthenes).
NEXT : Write a R program to extract first 10 english letter in lower case and last 10 letters in upper case and extract letters between 22nd to 24th letters in upper case.
R Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Test your Programming skills with w3resource's quiz.
What is the difficulty level of this exercise?