recursion
Oct 11, 2017 at 4:59am Oct 11, 2017 at 4:59am UTC
Why does this function count upwards and not downwards? Any help is appreciated thanks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <cstdio>
#include <cmath>
void f1(int x);
int main()
{
f1(4);
}
void f1(int x)
{
if (x > 0) {
int newX = x - 1;
f1(newX);
printf("%d\n" , newX);
}
}
Oct 11, 2017 at 5:10am Oct 11, 2017 at 5:10am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
#include <cstdio>
#include <cmath>
void f_upwards(int x) {
if (x > 0) {
int newX = x - 1;
f_upwards(newX);
std::printf("%d\n" , newX); // print after the recursive call
}
}
void f_downwards(int x) {
if (x > 0) {
int newX = x - 1;
std::printf("%d\n" , newX); // print before the recursive call
f_downwards(newX);
}
}
int main() {
std::puts( "upwards: " ) ;
f_upwards(4);
std::puts( "\ndownwards: " ) ;
f_downwards(4);
}
Oct 11, 2017 at 5:48am Oct 11, 2017 at 5:48am UTC
Why doesn't void f_upwards(int x)
just loop until 0 then terminate?
Oct 11, 2017 at 6:06am Oct 11, 2017 at 6:06am UTC
f_upwards(4) calls f_upwards(3)
f_upwards(3) calls f_upwards(2)
f_upwards(2) calls f_upwards(1)
f_upwards(1) calls f_upwards(0)
f_upwards(0) does nothing and returns to f_upwards(1)
f_upwards(1) prints 0 and returns to f_upwards(2)
f_upwards(2) prints 1 and returns to f_upwards(3)
f_upwards(3) prints 2 and returns to f_upwards(4)
f_upwards(4) prints 3 and returns to main()
Oct 11, 2017 at 6:11am Oct 11, 2017 at 6:11am UTC
Okay thank you!
Topic archived. No new replies allowed.