Swift 列印上三角數字圖案程式
本教程將討論如何編寫 Swift 程式來列印上三角數字圖案。
數字圖案是由數字組成的序列,用於構建不同的圖案或形狀,例如金字塔、矩形、十字架等。這些數字圖案通常用於理解或練習程式流程控制,它們也對邏輯思維很有幫助。
要建立上三角數字圖案,我們可以使用以下任何一種方法:
使用巢狀 for 迴圈
使用 stride 函式
以下是演示:
輸入
假設我們的輸入是:
Num = 5
輸出
期望的輸出是:
0 01 012 0123 01234 012345
方法 1 - 使用巢狀 for 迴圈
我們可以使用巢狀 for 迴圈來建立上三角數字圖案或任何其他圖案。
示例
下面的程式演示瞭如何使用巢狀 for 迴圈列印上三角數字圖案。
import Foundation import Glibc // Height of the upper numeric triangle pattern let num = 4 // Outer for loop is used to handle the // total number of rows in upper numeric // triangle pattern for i in 0...num{ // Nested for loop is used to print white // spaces for _ in 0..<(num-i){ print(" ", terminator: "") } // Nested for loop is used to print // upper numeric triangle pattern for x in 0...i{ print(x, terminator: "") } // Add new line print("") }
輸出
0 01 012 0123 01234
在上面的程式碼中,我們使用巢狀 for 迴圈來列印上三角數字圖案。最外層的 for 迴圈(從 0 到 4)用於處理要列印的行數,每一行都以換行符開頭。第一個巢狀 for 迴圈(從 0 到 <(num-i))用於列印空格,每次迭代空格減少一個。第二個巢狀 for 迴圈(從 0 到 i)用於列印上三角數字圖案,從數字 0 到 4。
方法 2 - 使用 stride 函式
Swift 提供了一個名為 stride() 的內建函式。stride() 函式用於以遞增或遞減的方式從一個值移動到另一個值。或者我們可以說 stride() 函式返回一個從起始值開始但不包括結束值的序列,並且序列中的每個值都以給定的步長遞增。
語法
語法如下:
stride(from:startValue, to: endValue, by:count)
這裡:
from − 表示給定序列的起始值。
to − 表示限制給定序列的結束值
by − 表示每次迭代的步長,正值表示向上迭代或遞增,負值表示向下迭代或遞減。
示例
下面的程式演示瞭如何使用 stride() 函式列印上三角數字圖案。
import Foundation import Glibc // Height of the upper star triangle pattern let num = 9 for i in 1...num{ // Printing white spaces for _ in stride(from: num, to: i, by: -1){ print(terminator : " ") } // Printing upper star triangle pattern for x in 1...i{ print(x, terminator : "") } // New line after each row print(" ") }
輸出
1 12 123 1234 12345 123456 1234567 12345678 123456789
在上面的程式碼中,我們使用了三個巢狀 for 迴圈。最外層的 for 迴圈用於處理要列印的行數(因此這個迴圈列印總共 9 行),每一行都以換行符開頭。第一個巢狀 for 迴圈用於列印空格,這裡使用 stride() 函式來列印空格。在這個函式中,迭代從 num 開始到 i,每次迭代值減少一個。
for _ in stride(from: num, to: i, by: -1) { print(terminator : " ") }
第二個巢狀 for 迴圈用於使用從 1 到 9 的數字列印上三角數字圖案:
for x in 1...i { print(x, terminator : "") }