What will be the output?

function add(num){
return 0;
return num+add(num-1)

1 Like

Hi @manaskumarpanigrahi6 , thank you for sharing your query. We will share the solution shortly.

1 Like

If you call the add function with the argument 3, it will execute as follows:

  1. First, the function will check if the argument num is less than or equal to 0. Since num is 3, this condition is not met, so the function proceeds to the next step.
  2. The function returns the sum of num and the result of calling add with the argument num-1. In this case, num is 3, so the function will return 3 + add(2).
  3. Now the add function is called again, but this time with the argument 2. The same steps are followed as before, and the function will return 2 + add(1).
  4. The add function is called again, this time with the argument 1. Again, the same steps are followed, and the function will return 1 + add(0).
  5. Finally, the add function is called with the argument 0. Since num is now 0, the function will return 0.
  6. The previous recursive calls will start returning their results in reverse order. add(0) returned 0, so add(1) will return 1 + 0, which is 1.
  7. add(2) will return 2 + 1, which is 3.
  8. Finally, add(3) will return 3 + 3, which is 6.

Therefore, calling add(3) will return 6.

1 Like

This is the problem of adding n consecutive numbers,This can be solved in various ways, As per your code this is solving this sum via recursion , For time complexity this solution is not so good,I will suggest you to use a Formula instead, function Sum(n){
return (n*(n+1))/2} Sum(3) Thats all ,one line same output 6 you will get