+ 2
Can anyone explain step by step how this code works, starting with print 1, where does it come from?
#include <iostream> using namespace std; void recurse(int u) { if (u > 0){ recurse(u-1); } cout << u; } int main() { recurse(5); }
3 Respostas
+ 2
Code starts with the 'recurse' call in main with value 5.
As long as the passed value is larger than 0, the function is called again recursively from the inside.
That's as if you open a browser window from a browser... and from that one another browser window...
Since every argument is smaller by 1, eventually it will be zero.
At that point, the the innermost call (the last 'browser window') will go on, first printing u of that specific window, then this function frame is closed, and we go back to the former one, that will also go on, printing its u ...
It's easier to understand if you think it through on a piece of paper.
+ 1
#include <iostream>
using namespace std;
void recurse(int u) {
if (u > 0){
recurse(u-1);
}
cout << u;
}
int main() {
recurse(5);
recurse(5) {
if (5 > 0){
recurse(5-1);
recurse(4) {
if (4 > 0){
recurse(4-1);
...
recurse(1) {
if (1 > 0){
recurse(1-1);
recurse(0) {
if (0 > 0){
recurse(0-1);
}
cout << 0;
}
}
cout << 1;
}
...
}
cout << 4;
}
}
cout << 5;
}
}
+ 1
HonFu, 👏😃
Thanks, finally I realized my mistake!
Going through the code in my imagination, for some reason I took "cout" out of the bounds of the function and it was one for me. ☺️