Flat Asterisk Pyramid
Part of the Fundamentals section of Coddy's Swift journey — lesson 84 of 86.
Challenge
EasyWrite a function flatPyramid that takes rows and returns a string representing a flat asterisk pyramid.
The pyramid grows from 1 asterisk up to the specified number of rows, then shrinks back down to 1. Each row should be on its own line, separated by newline characters (\n).
Logic:
- Build the ascending part: rows with 1, 2, 3, ... up to
rowsasterisks - Build the descending part: rows with
rows - 1,rows - 2, ... down to 1 asterisk - Join all rows with newline characters
Example: For rows = 3, the output should be:
*
**
***
**
*This is returned as the string: "*\n**\n***\n**\n*"
Parameters:
rows(Int): The maximum width of the pyramid (the middle row)
Returns: A string containing the complete pyramid pattern with rows separated by \n
Try it yourself
func flatPyramid(rows: Int) -> String {
// Write code here
}
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 Input