I'm currently writing a program to return all additions to a number subtracted from itself (For example, if 3 were the number, the output should be 6 (3+2+1). Essentially, I'm trying to have the function return the permutation of a number, but with addition, instead of mulitplication. This seemed like a perfect situation for a recursive function (something I struggling to understand). In my function, I would expect that the return value is not relevant (during the while loop) as the information is directly contained in the variables (specifically, static b). Yet, when I change the while loop in my function, to anything other than b, the wrong value gets returned from the function, into main() - it's always 0. What's even more confusing is that when I do a printf of b, right before the return of the (second - outside of while loop) b return value, my function prints the correct value (regardless of the return value above). Why must my function return b in the while loop (first return function) for the function to return the correct value, which is 55 (10+9+8+7+6+5+4+3+2+1+0)?
As the code is below, it works correctly.
#include <stdlib.h>
#include <stdio.h>
int sumyears(int a)
{
static int b=0;
while(a>0)
{
b+=a;
sumyears(a-1);
return b; //Program works correctly when I return b, but not when I return any other value, including a
}
printf("%d", b); //Program will always print correct value, but return different values based upon the return value in the while loop
return b;
}
int main()
{
printf("%d", sumyears(10));
}
return all additions to a number subtracted from itself
- I have no idea what you're even trying to achieve.java-forum
with questions about programs that had no obvious practical use. Those were not homework either. I learned a lot.