-1

I find it difficult to understand the working of this recursive function in PHP. I am not able to follow the code written at return statement. How the total of numbers from 1 to 10 is added? I eagerly want to understand this line return $count + sum($count + 1);

My whole code is:

<?php
function sum($count)
{
    if($count <= 10)
    {
        echo $count;
        echo "<br />";
        return $count + sum($count + 1);
    }
}
$result = sum(1);
echo "The total is $result";
?>

Output:

1
2
3
4
5
6
7
8
9
10
The total is 55

How the total 55 is received in my code? I want to learn it step by step.

Sachin
  • 1,646
  • 3
  • 22
  • 59

1 Answers1

0

Define the function

 function sum($count)
 {

Check if $count <=10 so the function will not excuted if

$count > 10 
if($count <= 10)
{

Print $count followed by a line break

    echo $count;
    echo "<br />";

Return $count + the result of the same function for $count+1 this which make the function work until reach the if condition $count<=10

    return $count + sum($count + 1);
    }
}

Note that while you pass 1 as a parameter and the function call itself within it so it will be continues until it reaches 10 $result = sum(1); echo "The total is $result"; ?>

Osama
  • 2,912
  • 1
  • 12
  • 15
  • the return line that i couldn't understand and that's why i asked this question is still unanswered. what is the result of sum($count + 1) when the function is executed first time i.e. when $count = 1? – Sachin Jul 26 '18 at 16:55
  • you said `Return $count + the result of the same function for $count+1` what is the result of sum() at first call. i mean return $count + sum($count + 1) – Sachin Jul 26 '18 at 16:57
  • how the addition concatenation works here? – Sachin Jul 26 '18 at 17:00
  • you explained unnecessary steps here. those are already understood. can you please explain the return sum concatenation plz. – Sachin Jul 26 '18 at 17:02