PHP Program to Print Pascal’s Triangle
Pascal’s Triangle is a mathematical construct named after the French mathematician Blaise Pascal. It is a triangular array of binomial coefficients, where each number is the sum of the two directly above it. In this article, we will explore different approaches to print Pascal’s Triangle in PHP.
Table of Content
- Using Simple Loop
- Using Recursion
- Using Dynamic Programming
Using Simple Loop
One of the simplest ways to generate Pascal’s Triangle is by using nested loops. This approach iterates through each row and column, calculating the binomial coefficient for each position.
PHP
<?php function pascalsTriangle( $rows ) { for ( $i = 0; $i < $rows ; $i ++) { $number = 1; for ( $j = 0; $j <= $i ; $j ++) { echo $number . " " ; $number = $number * ( $i - $j ) / ( $j + 1); } echo "\n" ; } } // Driver code $rows = 5; pascalsTriangle( $rows ); ?> |
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1
Using Recursion
An alternative approach involves using recursion to calculate the binomial coefficients. This method is less common but showcases the power of recursive functions.
PHP
<?php function binomialCoefficient( $n , $k ) { if ( $k == 0 || $k == $n ) { return 1; } else { return binomialCoefficient( $n - 1, $k - 1) + binomialCoefficient( $n - 1, $k ); } } function pascalsTriangle( $rows ) { for ( $i = 0; $i < $rows ; $i ++) { for ( $j = 0; $j <= $i ; $j ++) { echo binomialCoefficient( $i , $j ) . " " ; } echo "\n" ; } } // Driver code $rows = 5; pascalsTriangle( $rows ); ?> |
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1
Using Dynamic Programming
Dynamic programming can be employed to optimize the calculation of binomial coefficients and improve the overall efficiency of Pascal’s Triangle generation.
PHP
<?php function pascalsTriangle( $rows ) { $triangle = array (); for ( $i = 0; $i < $rows ; $i ++) { $triangle [ $i ] = array (1); for ( $j = 1; $j < $i ; $j ++) { $triangle [ $i ][ $j ] = $triangle [ $i - 1][ $j - 1] + $triangle [ $i - 1][ $j ]; } if ( $i != 0) { $triangle [ $i ][ $i ] = 1; } } // Display the Triangle foreach ( $triangle as $row ) { echo implode( " " , $row ) . "\n" ; } } // Driver code $rows = 5; pascalsTriangle( $rows ); ?> |
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1
Contact Us