Reputation: 105
I have a program that uses a tail recursion function to add the value entered and all the previous values. For example if the user enters 3, the function calculates 3+2+1 and gets an answer of 6. However this only sometimes works.
Here is my code below:
int addNum(int n);
int main(int argc, char *argv[]) {
int num;
printf("Enter an integer greater than zero, (q to quit): \n");
while(scanf("%d", &num) > 0){
if(num < 0){
continue;
}
else if(num == 0){
printf("Answer = 0 \n");
}
else{
printf("Answer = %d \n", addNum(num));
}
printf("Enter a positive number: \n");
}
return 0;
}
int addNum(int n){
int answer;
if(n > 0){
answer = n += addNum(n - 1);
}
return answer;
}
The output I get from this code is very peculiar. For numbers 0-6 I get the right answers. Once I get to 7 and 8 both the answers are incorrect. I keep going and 9-12 the answers are correct again. Then 13 and 14 are incorrect. It keeps going back and fourth like this. I have absolutely no clue what is going on if someone could help. If it is something simple and wrong with my code please don't give me the answer but rather a hint at the problem.
I will post the output below so you can see what is going on. I decided to use pastebin for my output to save room. http://pastebin.com/DjJfxJAT
Upvotes: 1
Views: 56
Reputation: 27
I think this code itself explains things
int addNum(int n);
int answer=0;
int main(int argc, char *argv[]) {
int num;
printf("Enter an integer greater than zero, (q to quit): \n");
while(scanf("%d", &num) > 0){
if(num < 0){
continue;
}
else if(num == 0){
printf("Answer = 0 \n");
}
else{
answer=0;
printf("Answer = %d \n", addNum(num));
}
printf("Enter a positive number: \n");
}
return 0;
}
int addNum(int n){
if(n > 0){
answer = n += addNum(n - 1);
}
return answer;
}
Upvotes: -1
Reputation: 48572
You don't initialize answer
in addNum()
, so whenever you call it with n == 0, undefined behavior occurs since you end up returning an uninitialized value. It's only by luck that you ever get the right answer.
Upvotes: 3