2. Printing Shapes
Printing out asterisk characters (*) in shapes is often used as beginner’s programming exercises, as they are simple, easy to understand and visually interesting.
2.1 Print out Triangle
Write a program to print out asterisks like the triangle shape below:
*
**
***
****
*****
******
*******
********
*********
**********
Purpose
- Develop ability to analyze patterns
- Variables
- Use of looping
Analyze
| Row | The number of stars |
|---|---|
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| … | … |
| n | n |
Hints
Print out text.
print("*")
print("**") // will be in a separate line
Generate multiple occurrences of the same character.
// get multiple '$'s
String(repeating: "$", count: 3) // => "$$$"
Using a variable to store an integer.
var starCount = 2
print(String(repeating: "*", count: starCount)) // => '**'
starCount = starCount + 1 // now starCount => 3
print(String(repeating: "*", count: starCount)) // => '***'
Print out text multiple times in a loop (fixed number of times).
for index in 1...3 {
print(index)
}
Output:
1
2
3
The { … } mark the beginning and end of loop respectively. The variable index is the looping index, often used in the code within the loop. print(index) is the code fragment that executes for specified 3 times.
2.2 Print out a half diamond
Write a program that prints out half of the diamond shape using asterisks.
*
**
***
****
*****
******
*******
********
*******
******
*****
****
***
**
*
Purpose
- Decrement count in loops
Analyze
The key to this problem is to determine the number of stars for the corresponding rows.
row 1 to 8: the same as row number
row 9 to 16: 16 - row
Hints
Control flows using if … else
Code, in its simplest form, is executed from top to bottom. But if there are if conditions and loops (and later methods and classes), it will change the flow of execution. The conditional expressions (if-then-else statements) run different code statements depending on a boolean condition (true or false).
var score = 75
if score < 60 {
print("Failed!")
} else {
print("Pass!")
}
Output:
Pass!
If you change the var score = 59 and run again, you will get Failed!.
Boolean condition
The statement score < 60 after if is called a boolean condition. Its value can only be either true or false (which are called boolean values).
Common comparison operators in Swift
| == | equal to |
| != | not equal to |
| < | less than |
| <= | less than or equal to |
| > | greater than |
| >= | greater than or equal to |
Examples:
2 > 1 // => true
2 == 1 // => false (equal to)
2 != 1 // => true (not equal to)
2 <= 2 // => true
2.3 Print out diamond shape
Print 7 rows of ‘*’ in a diamond shape as below:
*
***
*****
*******
*****
***
*
Purpose
- Analyse more complex patterns
- Math operators
Analyze
Below are formulas to calculate the number of star; where rowNumber represents the row number and totalRows represents the total number of rows,
- The number of stars for the rows before the middle one is
(rowNumber - 1) * 2 + 1. - the number of stars for the rows after the middle one is
(totalRows - rowNumber) * 2 + 1
Think about the spaces in front of each row, except for the 4th row (the longest middle one).
Hints
Write down the number of spaces and stars for each row.
row 1: print 3 spaces + 1 star
row 2: print 2 spaces + 3 stars
row 3: print 1 space + 5 stars
row 4: print 0 space + 7 stars
row 5: print 1 space + 5 stars
row 6: print 2 spaces + 3 stars
row 7: print 3 spaces + 1 star
Math operators: multiply and divide
The Math multiply and divide operator are * and / respectively.
8 / 2 // => 4
9 / 2 // => 4, ignore the remainder
(1 + 2) * 3 + 3 / 2 // => 10
2.4 Print big diamond, name your size
Ask the user for the size of diamond (based on the total number of rows) and then print out a diamond shape using asterisks ‘*’.
Enter the maximum number of rows (odd number): 9
*
***
*****
*******
*********
*******
*****
***
*
Purpose
- Read user’s input into a variable
- Convert string to integer
- Use variable control loop times
- Swift optionals
Analyze
The size of the diamond is not fixed, it depends on the number the user entered. The number the program asks the user to enter is the total number of rows, which can be stored in an variable.
If you divide the diamond into two parts (top and bottom), work out the number of rows for each part.
Hints
Read user’s input
We can use readLine() function to read user’s input from a command line application.
let userInput = readLine()
String and Integer
The String and Integer are two most common data types.
var a = "12"
var b = "3"
a + b // => "123"
var c = 12
var d = 3
c + d // => 15
Math operations, such as Add, between String and Integer will get compile error.
var b = "3"
var c = 12
b + c // Binary operator '+' cannot be applied to 'String' and 'Int'
Convert a number string to integer
var a = "12"
Int(a) // => to integer 12
**
Swift Optionals
Optionals in Swift is quite difficult concept for me, as it is not in other languages I have used. The purpose of Optionals is to avoid assign nil (means no value) to a variable. It is better explained with example.
var str1:String
str1 = nil // error: Nil cannot be assigned to type "string"
Assign nil to an Optional is OK, with an extra ?.
var str2:String?
str2 = nil // OK
However, you can force assigning an optional variable to non-optional one by using !.
var str3:String
str3 = str2 // error: Value of optional type "String?" not unwrapped
str3 = str2! // OK
You might still find it confusing. Good news is that Xcode will give you hints and even offer ‘Fix it’.
2.5 Exercises
Write code to print out the shapes below, the width of shape is changeable.
Rhombus
*****
*****
*****
*****
*****
Hollow Square
*****
* *
* *
* *
*****
Heart
***** *****
******* *******
********* *********
*******************
*****************
***************
*************
***********
*********
*******
*****
***
*
Hints
The first three rows are static regardless of the size.