Swift - repeat...while 迴圈



forwhile迴圈不同,forwhile迴圈在迴圈頂部測試迴圈條件,而repeat...while迴圈在迴圈底部檢查其條件。repeat...while迴圈類似於while迴圈,不同之處在於repeat...while迴圈保證至少執行一次,然後再檢查迴圈條件。

語法

repeat...while迴圈的語法:

repeat{
   statement(s);
} while( condition );

需要注意的是,條件表示式出現在迴圈的末尾,因此迴圈中的語句會在條件被測試之前執行一次。如果條件為真,控制流將跳回到repeat,迴圈中的語句再次執行。這個過程會重複,直到給定的條件變為假。

流程圖

下面的流程圖將展示repeat-while迴圈的工作原理:

Repeat-While Loops

示例

Swift程式演示repeat while迴圈的使用。

import Foundation

var index = 10

repeat {
   print( "Value of index is \(index)")
   index = index + 1
} while index < 20 

輸出

它將產生以下輸出:

Value of index is 10
Value of index is 11
Value of index is 12
Value of index is 13
Value of index is 14
Value of index is 15
Value of index is 16
Value of index is 17
Value of index is 18
Value of index is 19

示例

使用repeat while迴圈求1到10的數字之和的Swift程式。

import Foundation
var sum = 0
var num = 1
repeat {
   sum += num
   num += 1
} while num <= 10
print("Sum of numbers from 1 to 10 is: \(sum)")

輸出

它將產生以下輸出:

Sum of numbers from 1 to 10 is: 55
廣告