In this answer, we have shared how to print star triangle using swift program. Not quite equilateral but as close as you’re likely to get with character graphics. The main things are that you need an odd number of asterisks on each line for centering to work and you need to calculate an offset.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | let treeHeight = 5 let treeWidth = treeHeight * 2 - 1 for lineNumber in 1...treeHeight { // How many asterisks to print let stars = 2 * lineNumber - 1 var line = "" // Half the non-star space let spaces = (treeWidth - stars) / 2 if spaces > 0 { line = String(repeating: " ", count: spaces) } line += String(repeating: "*", count: stars) print (line) } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.