# Kotlin Program: Print Pascal's Triangle for a given number of rows

## Kotlin Control Flow: Exercise-5 with Solution

Write a Kotlin program to print the Pascal's triangle of a given number of rows.

**Sample Solution:**

**Kotlin Code:**

```
fun printPascalTriangle(rows: Int) {
require(rows > 0) { "Number of rows must be greater than 0." }
var prevRow = mutableListOf(1)
println(prevRow.joinToString(" "))
for (currentRow in 1 until rows) {
val nextRow = mutableListOf
```()
nextRow.add(1)
for (i in 1 until currentRow) {
val sum = prevRow[i - 1] + prevRow[i]
nextRow.add(sum)
}
nextRow.add(1)
println(nextRow.joinToString(" "))
prevRow = nextRow
}
}
fun main() {
val numRows = 7
printPascalTriangle(numRows)
}

Sample Output:

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

**Explanation:**

In the above exercise,

- The "printPascalTriangle()" function takes the rows parameter, which specifies the number of rows to be printed in Pascal's triangle. It first checks if the number of rows is greater than 0 using the require function.
- The program then initializes prevRow as a mutable list containing the first row with a single element, which is always 1. This row is printed using the "println()" and "joinToString()" functions to concatenate the row elements with spaces.
- The program then enters a loop to calculate and print the subsequent rows. It initializes an empty mutable list nextRow. It adds 1 as the first element of the row, and then calculates the remaining elements by summing the corresponding elements from the previous row (prevRow). The calculated elements are added to nextRow.
- Finally, the nextRow is printed, and prevRow is updated to nextRow for the next iteration. The loop continues until the desired number of rows is printed.
- In the "main()" function, a sample value of numRows (7) is provided, and printPascalTriangle is called with this value. The program then prints Pascal's triangle with7 rows.

**Kotlin Editor: **

**Previous:** Print the first 10 natural numbers.

**Next:** Fibonacci series up to a given number.

**What is the difficulty level of this exercise?**

Test your Programming skills with w3resource's quiz.

**Weekly Trends and Language Statistics**- Weekly Trends and Language Statistics