Looping The Numbers
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 65 of 93.
Challenge
MediumIn the previous lesson, you created the fizzBuzz function that returns the appropriate string for a single number. Now, make your program dynamic by reading the upper limit from input instead of hardcoding 15.
Modify your code to:
- Read an integer
nfrom input (the upper limit) - Loop from 1 to
n(inclusive) - For each number, call your
fizzBuzzfunction and print the result
Keep your existing fizzBuzz function unchanged - it should still return:
"FizzBuzz"if divisible by both 3 and 5"Fizz"if divisible by 3 only"Buzz"if divisible by 5 only- The number as a string otherwise
Input: A single integer representing the upper limit
Output: The FizzBuzz result for each number from 1 to n, each on its own line
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() {
for (i in 1..15) {
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