Adding The Twist
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 66 of 93.
Challenge
MediumIn the previous lesson, you made the upper limit dynamic by reading it from input. Now, add the twist by making the divisors customizable too!
Modify your code to:
- Read three integers from input:
n- the upper limitfizzDivisor- the divisor for "Fizz"buzzDivisor- the divisor for "Buzz"
- Update your
fizzBuzzfunction to accept three parameters: the number to check, the fizz divisor, and the buzz divisor - Loop from 1 to
nand print the result for each number using the custom divisors
Updated function signature:
fun fizzBuzz(num: Int, fizzDiv: Int, buzzDiv: Int): StringReturn logic (same as before, but with custom divisors):
"FizzBuzz"if divisible by both divisors"Fizz"if divisible byfizzDivonly"Buzz"if divisible bybuzzDivonly- The number as a string otherwise
Input: Three integers on separate lines - the upper limit, fizz divisor, and buzz divisor
Output: The customized FizzBuzz result for each number from 1 to n, each on its own line
Input constraints: Both divisors are positive integers. The count is between 1 and 100.
Try it yourself
fun fizzBuzz(n: Int): String {
return if (n % 3 == 0 && n % 5 == 0) {
"FizzBuzz"
} else if (n % 3 == 0) {
"Fizz"
} else if (n % 5 == 0) {
"Buzz"
} else {
n.toString()
}
}
fun main() {
val n = readLine()!!.toInt()
for (i in 1..n) {
println(fizzBuzz(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