-2

I couldnot find a logical reason as how this return statement is working. As much as i read,it should return undefined but the program takes it straight to the recursive call function below

 #include <iostream>
 using namespace std;

// Recursive function to print the pattern without any extra
// variable
void printPattern(int n)
{
 // Base case (When n becomes 0 or negative)
 if (n ==0 || n<0)
 {
    cout << n << " ";
    return;
 }

 // First print decreasing order
  cout << n << " ";
  printPattern(n-5);

 // Then print increasing order
 cout << n << " ";
 }

// Driver Program
int main()
{
int n = 16;
printPattern(n);
return 0;
}

the output of above code is

16 11 6 1 -4 1 6 11 16

  • It just returns from the function at the point the statement is executed. It doesn't matter if the call was recursive. – πάντα ῥεῖ Aug 12 '22 at 07:19
  • 5
    It does the same thing as any non-recursive `void` function's `return` statement does. It exits the function, returning no value. – jkb Aug 12 '22 at 07:19
  • *In a recursive function* there are no special rules for recursive functions. None at all, they work exactly the same as any other kind of function. Recursion describes a certain technique for solving problems, it does not describe a special kind of function. – john Aug 12 '22 at 07:30

2 Answers2

0

Recursion isn't special. Here's your function again, but I hid the name so you can't see which function it is.

void XXXXXXXXXX(int n)
{
 // Base case (When n becomes 0 or negative)
 if (n ==0 || n<0)
 {
    cout << n << " ";
    return;
 }

 // First print decreasing order
  cout << n << " ";
  printPattern(n-5);

 // Then print increasing order
 cout << n << " ";
 }

What does XXXXXXXXXX(-1) do? That's right: it prints -1

What does XXXXXXXXXX(16) do? That's right: it prints 16, then it prints the pattern for 11, then it prints 16 again.

Now can you see why XXXXXXXXXX(16) prints 16 at the start and the end?

user253751
  • 57,427
  • 7
  • 48
  • 90
0

return (irregardless if the function is recursive or not) will pass an optional value to caller, and execution will then continue in caller.

Allan Wind
  • 23,068
  • 5
  • 28
  • 38
  • Optional sounds like you could choose if you want to give a value or not in the return statement, but you can only choose the return type of the function to be void or not void, and then you must stick with that for all return in that function. – gerum Aug 12 '22 at 07:37