### Displaying recursion steps. I would like to print the local variable and the recursive call parameter for each recursive call. Cout is not a return type so I can not use it in this return statement. How can I put a new return statement to print these? I am more interested in solving the dispay problem than to see the recursion steps.

 ``12345678910111213141516171819202122`` `````` #include #include using namespace std; unsigned long factorial(unsigned long); int main(){ for(unsigned long counter{0}; counter<=10; counter++){ cout << setw(2) << counter << "! = " << factorial(counter) << endl; } } unsigned long factorial(unsigned long number){ if(number <=1){ return 1; } else{ return number * factorial(number - 1); } } `````` You have tried printing?
 ``12345678910111213141516171819202122`` ``````#include #include using namespace std; unsigned long factorial(unsigned long); int main(){ for(unsigned long counter{0}; counter<=10; counter++){ cout << setw(2) << counter << "! = " << factorial(counter) << endl; } } unsigned long factorial(unsigned long number){ cout << ' ' << number; // print if(number <=1){ return 1; } else{ return number * factorial(number - 1); } }``````

How did it fail?

Or would you rather store data and print it later?
 ``1234567891011121314151617181920212223242526`` ``````#include #include #include using namespace std; unsigned long factorial(vector&, unsigned long); int main(){ for(unsigned long counter{0}; counter<=10; counter++){ vector calls; cout << setw(2) << counter << "! = " << factorial(calls, counter) << endl; for ( auto c : calls ) cout << ' ' << c; cout << '\n'; } } unsigned long factorial(vector& v, unsigned long number){ v.emplace_back( number ); if(number <=1){ return 1; } else{ return number * factorial(v, number - 1); } }``````
Last edited on ``12345678910111213141516171819202122232425262728`` ``````#include #include using namespace std; template void p(int depth, Args&&... args) { cout << setw(depth * 4) << ""; (cout << ... << args) << '\n'; } unsigned long factorial(unsigned n, unsigned depth=0) { if (n <= 1) { p(depth, n, " (1)"); return 1; } else { p(depth, n); auto x = factorial(n - 1, depth + 1); p(depth, n, " (", n * x, ')'); return n * x; } } int main(){ int n = 10; auto f = factorial(n); cout << setw(2) << n << "! = " << f << '\n'; }``````

 ```10 9 8 7 6 5 4 3 2 1 (1) 2 (2) 3 (6) 4 (24) 5 (120) 6 (720) 7 (5040) 8 (40320) 9 (362880) 10 (3628800) 10! = 3628800```
Last edited on