Are you searching for PHP program to print sum triangle for a given array, then this answer for you.
Copy the below PHP program and run it with the help of PHP compiler to see the program output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | /** * PHP program to print sum triangle for a given array. */ function printTriangle($arr, $n) { // Initialize a 2D array to store triangle $tri[$n][$n] = array(array()); array_fill(0, count($tri), 0); // Initialize last row of triangle for ($i = 0; $i < $n ; $i++) $tri[$n - 1][$i] = $arr[$i]; // Fill other rows for ($i = $n - 2; $i >= 0; $i--) for ($j = 0; $j <= $i; $j++) $tri[$i][$j] = $tri[$i + 1][$j] + $tri[$i + 1][$j + 1]; // Print the triangle for ($i = 0; $i < $n; $i++) { for( $j = 0; $j <= $i ; $j++) echo $tri[$i][$j] . " "; echo "\n"; } } // Driver Code $arr = array(4, 7, 3, 6, 7); $n = count($arr); printTriangle($arr, $n); |
Program Output
1 2 3 4 5 | 81 40 41 21 19 22 11 10 9 13 4 7 3 6 7 |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.