How to print the Pascal's triangle in Swift

Learn how to print the pascal’s triangle in the console with Swift.

In mathematics, Pascal’s triangle is a triangular arrangement of numbers that gives the coefficients in the expansion of any binomial expression, such as (x + y)n. It is named for the 17th-century French mathematician Blaise Pascal. As an easier explanation for those who are not familiar with binomial expression, the pascal’s triangle is a never-ending equilateral triangle of numbers that follow a rule of adding the two numbers above to get the number below.

In this article, we’ll show you how to generate this famous triangle in the console with the Swift programming language.

Printing directly in the console

Graphically, the way to build the pascals triangle is pretty easy, as mentioned, to get the number below you need to add the 2 numbers above and so on:

How to print the Pascal's triangle in Swift

The following code will generate the pascal’s triangle:

// Function that generates the pascals triangle with a specific number of rows
func generatePascalTriangle(numRows: Int){
    var results = [[Int]]()
    
    if (numRows == 0) {
        return
    }

    for i in 0..<numRows {
        var currentResults = [Int]()

        // Print spaces
        for _ in 0..<(numRows - i - 1) {
            print(" ", terminator:"")
        }

        // Print values
        for j in 0...i {
            if (i > 1 && j > 0 && j < i) {
                let value = results[i-1][j] + results[i-1][j-1]
                currentResults.append(value)

                print("\(value) ", terminator: "")
            } else {
                currentResults.append(1)
                print("\(1) ", terminator: "")
            }
        }
        
        results.append(currentResults)
        print("\n")
    }
}

// Prompt the user for the number of rows through the console e.g "10"
print("Insert the number of rows for the triangle:")
let numberOfRows:Int? = Int(readLine()!)

// Print the pascals triangle in the console with the given number of rows
generatePascalTriangle(numRows: numberOfRows!)
// Or force the value directly:
// generatePascalTriangle(numRows: 10)

Copy snippet

The execution of the previous code will generate the following output in the console:

How to print the Pascal's triangle in Swift

Retrieving triangle data in array

If instead of printing simply the triangle in the console, you may retrieve the data generated by the logic and render it of another way later:

// Function that generates the pascals triangle with a specific number of rows
func generate(numRows: Int) -> [[Int]] {
    var results = [[Int]]()
    
    if (numRows == 0) {
        return results
    }

    for i in 0..<numRows {
        var currentResults = [Int]()
        
        for j in 0...i {
            if (i > 1 && j > 0 && j < i) {
                let value = results[i-1][j] + results[i-1][j-1]
                currentResults.append(value)
            } else {
                currentResults.append(1)
            }
        }

        results.append(currentResults)
    }
    
    return results
}

let triangleContent = generate(numRows: 10)

print(triangleContent)

Copy snippet

The previous code will generate the following ouput:

How to print the Pascal's triangle in Swift

Remember that you can iterate over the result of the function, for example:

let triangleContent = generate(numRows: 10)

for i in 0..<triangleContent.count {
    let row = triangleContent[i]
    
    for i in 0..<row.count {
        let value = row[i]
        print("\(value) ", terminator:"")
    }

    print("\n")
}

Copy snippet

The previous snippet will generate the following output:

How to print the Pascal's triangle in Swift

Leave a Comment