How to calculate and print the Pascal triangle in Kotlin

2 Answers

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

fun pascalTriangle(rows: Int) {
    for (i in 0 until rows) {
        var number = 1

        for (j in 1 until (rows - i)) {
            print("   ")
        }

        for (k in 0..i) {
            print("    $number")
            number = number * (i - k) / (k + 1)
        }
        println("\n")
    }
}

fun main() {
    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
0 votes
fun pascalTriangle(rows: Int) {
    var number: Int

    for (i in 0 until rows) {
        for (space in 1..(rows - i)) {
            print("  ")
        }
        for (j in 0..i) {
            number = if (j == 0 || i == 0) {
                1
            } else {
                var num = 1
                for (k in 0 until j) {
                    num = num * (i - k) / (k + 1)
                }
                num
            }

            print(String.format("%4d", number))
        }
        println()
    }
}

fun main() {
    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
...