while 迴圈
while迴圈從計算單一條件開始。如果條件為true,會重複執行一系列語句,直到條件變為false。
下面是一般情況下 while 迴圈格式:
while condition { statements }
範例:
var index = 1
while index <= 10 {
print(index)
index = index + 1
}
//產生結果:1,2,3,4,5,6,7,8,9,10
練習題1:請改成取1~10的單數
解答:
var index = 1
while index <= 10 {
print(index)
index += 2
}
//產生結果:1,3,5,7,9
注意:while迴圈,一定要再寫到while變數「會做的事情」,不然會造成無限迴圈(程式當掉),像下面一樣
如何印出shoppingList的清單
- Six Eggs
- Milk
- Flour
- Bananas
範例:
var index = 0
var shoppingListArray = ["Six Eggs","Milk","Flour","Bananas"]
shoppingListArray.count
while index < shoppingListArray.count {
print(shoppingListArray[index])
index += 1
}
說明:
- step1:先定義index = 0 (等等跑廻圈使用)
- step2:把shoppingList的清單,用陣列寫出。
- step3:計算shoppingList的清單數量有多少(shoppingListArray.count)
- step4:寫出廻圈程式,計算index從0到shoppingList的清單數量,並印出
while repeat 廻圈
程式碼:
var myCounter = 1
repeat{
print("just do it \(myCounter) time")
myCounter += 1
}while myCounter < 11
在Xcode Playground的效果:
*Repeat while廻圈與while迴圈的差異:while迴圈,至少會執行一次。
例如:
練習題2:在var index =1的條件下請用while及repeat while,再做條列1~10的數值。
解答:
var index = 1
while index <= 10{
print(index)
index = index + 1
}
var index2 = 1
repeat{
print(index2)
index2 = index2 + 1
}while index2 <= 10
練習題3:以下程式碼,哪裡有錯誤?
var index = 1
while index = 10{
print(index)
index = index + 1
}
解答:
index <= 10
,不能寫成index = 10
,要寫成index == 10
,因為
=
在程式裡是指定某個值。- 而
==
是判斷。