FizzBuzz program (2 types)

Requirement 1

-Request the input of a positive integer (natural number). -If the given number is a multiple of 15, output "FizzBuzz" ・ For multiples of 3, output "Fizz" ・ For multiples of 5, output as "Buzz" ・ For other times, the numbers are output as they are.

Code example

num = gets.to_i

def fizzbuzz(num)
  if num % 15 == 0
    puts "FizzBuzz"
  elsif num % 3 == 0
    puts "Fizz"
  elsif num % 5 == 0
    puts "Buzz"
  else
    puts num
  end
end

fizzbuzz(num)

Requirement 2 (improved version of the previous code)

・ Ask for input of natural numbers. -Outputs one of "Fizz", "Buzz", "FizzBuzz", and "number" from 1 to that number. ** Example) Input value is 9 → 1,2, Fizz, 4, Buzz, Fizz, 7,8, Fizz ** -If you are given 0 or a character string, you can be asked to enter it again.

Code example

puts "Please enter a number other than 0"

input_number = gets.to_i
num = 1

def fizzbuzz(input_number,num)
  input_number.times do
      if num % 15 == 0
        puts "FizzBuzz"
      elsif num % 3 == 0
        puts "Fizz"
      elsif num % 5 == 0
        puts "Buzz"
      else
        puts num
      end
        num += 1
  end

  if input_number == 0
      puts "0 or a character string has been entered. Type it again."
      input_number = gets.to_i
      fizzbuzz(input_number,num)
  end
      
end

fizzbuzz(input_number,num)

Recommended Posts

FizzBuzz program (2 types)
Ruby: I made a FizzBuzz program!
FizzBuzz problem
Calculator program
Zundoko Program
FizzBuzz various