I was assigned funct() and was told to convert it into tail recursion, so I made funct2(). I used another stack overflow thread to begin and it kind of works, but it's always a value off.
I think the problem is due to the y value being 0 initially, and when going to the else part of the function, subtracts from 0 rather than a value that is equivalent to the initial x. But I'm not sure.
#include <iostream>
#include <stdio.h>
using namespace std;
int funct(int x);
int funct2(int x, int y);
int main() {
int x = 24;
printf("%d %d", funct(x), funct2(x, 0));
}
int funct(int x) {
if (x <= 0){
return 0;
}
else if (x & 0x01){
return x + funct(x-1);
}
else {
return x - funct(x-1);
}
}
int funct2(int x, int y) {
if (x < 0){
return 0;
}
else if (x == 0){
return y;
}
else if (x & 0x01){
return funct2(x-1, y+x);
}
else {
return funct2(x-1, y-(x-1));
}
}
Any help is appreciated. Thanks guys!