1

Output:

3 3 4 3 4 5 3 4 5 6 3 4 5 6 7 3 4 5 6 7 8 
function Triangle ($begin, $end) { if ($begin < 0 || $end < 0) { return; } if ($begin == $end) { return $a; } else { // non recursive for ($i = 1; $i <= $end; $i++) { for ($j = $begin; $j <= $i; $j++) { echo $j . " "; } echo "<br>"; } } } 

This is what I made so far.

0

2 Answers 2

2

Here's one way:

function triangle ($begin, $end, $row = 1) { //stop when we've printed up to end if($end - $begin + 1 < $row) return; //let's start at the beginning :) for($i = 0; $i < $row; $i++){ //the row number increments each time so we can keep adding. echo ($begin + $i)." "; } echo "<br>"; //now recurse... triangle($begin, $end, $row + 1); } 

Usage:

triangle(3,9); 

Output:

3 3 4 3 4 5 3 4 5 6 3 4 5 6 7 3 4 5 6 7 8 3 4 5 6 7 8 9 
Sign up to request clarification or add additional context in comments.

2 Comments

wow we posted it on the same second! (BTW: Your script prints a new line at the start)
Oh yeah! Changed. Ta!
1

This should work for you:

(Here I just added the variable step which defines how many steps you make from $begin to $end and if $begin + $step == $end the function is done. If not It starts from $begin and makes X steps and as long as it doesn't reach the end I call the function again with a step more)

<?php function Triangle($begin, $end, $step = 0) { for($count = $begin; $count <= ($begin+$step); $count++) echo "$count "; echo "<br />"; if(($begin + $step) == $end) return; else Triangle($begin, $end, ++$step); } Triangle(3, 8); ?> 

output:

3 3 4 3 4 5 3 4 5 6 3 4 5 6 7 3 4 5 6 7 8 

1 Comment

I'm upvoting your answer on the basis that it's the same as mine (short of different styles!)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.