Looping The Numbers
Part of the Fundamentals section of Coddy's Swift journey. Lesson 60 of 86.
Challenge
EasyIn the previous lesson, you created the fizzBuzz function that returns the correct string for a single number. Now, add a loop to process all numbers from 1 to a given limit.
Modify your code to:
- Read an integer from input representing the upper limit
- Use a
for-inloop to iterate from 1 through the limit (inclusive) - For each number, call your
fizzBuzzfunction and print the result
You will receive the following input:
- A single integer representing the upper limit
For example, if the input is 5, the output should be:
1
2
Fizz
4
BuzzIf the input is 15, the output should be:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzzTry it yourself
func fizzBuzz(_ number: Int) -> String {
if number % 3 == 0 && number % 5 == 0 {
return "FizzBuzz"
} else if number % 3 == 0 {
return "Fizz"
} else if number % 5 == 0 {
return "Buzz"
} else {
return String(number)
}
}
// Read input
let number = Int(readLine()!)!
// Call the function and print the result
print(fizzBuzz(number))All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorCompound AssignmentRecap - Simple MathComparison Operators7Basic IO
Print FunctionString InterpolationReadLine InputType ConversionRecap - Till 120Recap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesArgument LabelsRecap - Sigma FunctionRecap - Validation FunctionDefault Values13Iterating Over Sequences
Iterating Over ElementsThe Enumerated MethodIterating Over Strings P1Iterating Over Strings P22Variables
Let vs VarType AnnotationsNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary Operator8Bill Split Calculator
Welcome MessageGetting Input3Optionals
What Are OptionalsUnwrapping With If LetGuard LetNil Coalescing OperatorRecap - Safe Unwrapping9Loops
For-In LoopWhile LoopRepeat-While LoopBreakContinueRecap - FactorialRanges In LoopsNested LoopRecap - Dynamic InputPractice on your own: Swift playground