The FizzBuzz Function
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 64 of 93.
Challenge
MediumIn the previous lesson, you implemented the traditional FizzBuzz by printing results directly in a loop. Now, refactor your code by extracting the FizzBuzz logic into a reusable function.
Create a function called fizzBuzz that takes a single number and returns the appropriate string result.
Function requirements:
- Name:
fizzBuzz - Parameter:
n(Int) - the number to evaluate - Returns: A
Stringwith the result
Return logic:
- Return
"FizzBuzz"ifnis divisible by both 3 and 5 - Return
"Fizz"ifnis divisible by 3 only - Return
"Buzz"ifnis divisible by 5 only - Return the number as a string otherwise (use
n.toString())
Then, update your main function to use a loop from 1 to 15 that calls fizzBuzz for each number and prints the returned result.
Try it yourself
fun main() {
// TODO: Write your code below
// Implement FizzBuzz for numbers 1 to 15
// - Print "FizzBuzz" if divisible by both 3 and 5
// - Print "Fizz" if divisible by 3 only
// - Print "Buzz" if divisible by 5 only
// - Print the number itself otherwise
for (i in 1..15) {
if (i % 3 == 0 && i % 5 == 0) {
println("FizzBuzz")
} else if (i % 3 == 0) {
println("Fizz")
} else if (i % 5 == 0) {
println("Buzz")
} else {
println(i)
}
}
}All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic InputPractice on your own: Kotlin playground