How to calculate and print the Pascal triangle in Swift

1 Answer

0 votes
import Foundation

// Each number in Pascal's triangle is the sum of the two numbers directly above it 

func pascalTriangle(_ rows: Int) {
    var number: Int

    for i in 0..<rows {
        for _ in 0..<(rows - i) {
            print("  ", terminator: "")
        }
        for j in 0...i {
            if j == 0 || i == 0 {
                number = 1
            } else {
                var num = 1
                for k in 0..<j {
                    num = num * (i - k) / (k + 1)
                }
                number = num
            }
            print(String(format: "%4d", number), terminator: "")
        }
        print()
    }
}

pascalTriangle(7)



/*
run:

                 1
               1   1
             1   2   1
           1   3   3   1
         1   4   6   4   1
       1   5  10  10   5   1
     1   6  15  20  15   6   1

*/

 



answered Jan 5, 2025 by avibootz
...