• 0

recursion in c?


Question

im having some trouble with this simple problem...

im supposed to implement a simple c method with the input format:

void fact(int num, int *result)

that calculates the factorial of num

im new to c, so i dont really understand how pointers work...

all i know is that *result is the content at result, and &result is the address?

normally i'd just do:

if num = 1, return 1

else result = num*fact(num-1)

return result

but the method im told to make returns type void... and i have no idea how *result factors in

Link to comment
Share on other sites

2 answers to this question

Recommended Posts

  • 0
im having some trouble with this simple problem...

im supposed to implement a simple c method with the input format:

void fact(int num, int *result)

that calculates the factorial of num

im new to c, so i dont really understand how pointers work...

all i know is that *result is the content at result, and &result is the address?

normally i'd just do:

if num = 1, return 1

else result = num*fact(num-1)

return result

but the method im told to make returns type void... and i have no idea how *result factors in

In this case, you'd be returning your result in the second variable, it will be very similar to the code you posted:

</P><P>if num = 1, return 1
  else result = num*fact(num-1)
  return result</P><P>

except instead of returning the value you'd edit the second variable

if (num == 1)

{

? ? *result = 1;

}
else

{

? ? fact(num-1);

?? ?*result *= num;

}
return;

Also, * gives you the content if the variable you are using it is a pointer, & gives you the address of the current variable, if the current variable is a pointer then you'd have a pointer to a pointer.

In this case, you'd call your function like this:

int number = 5;

int result;

fact(number, &result);

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.