Can a function call itself?

This is a discussion on Can a function call itself? within the C Programming forums, part of the General Programming Boards category; Hi all, I have to program a recursion to find the answer to a maths question, the recursion formula I ...

1. Can a function call itself?

Hi all, I have to program a recursion to find the answer to a maths question, the recursion formula I am working with is:

f(a,b) = f(a,b-1) - f(a/g(b),b-1)

where g is an arbitary function that is easy to use

I also have the condition that f(a,0)=a

What is the best way to go about programming this kind of thing in C?

My initial idea was to have the function call itself if b wasn't 0, but that doesn't seem to work, will this method work or is there a much better SIMPLE way?

2. My inital try

Code:
```MainCL{
printf("%d", f(10,5));
}

int f(int a, int b){
if(b=0){
return a;}
else{
return f(a,(b-1))-f(a/2,(b-1));}
}```

3. Re: My inital try

Originally posted by ajm218
Code:
```MainCL{
printf("%d", f(10,5));
}```
What exactly is this?

Originally posted by ajm218
Code:
```int f(int a, int b){
if(b=0){
return a;}
else{
return f(a,(b-1))-f(a/2,(b-1));}
}```
Your if statement is wrong. '=' is assigmnent, '==' is an equality test.

Quzah.

4. Correction to initial Code

Sorry just to give a quick example of some input, so i gave f(10,5)

Code:
```MainCL{
printf("%d", f(10,5));
}

int f(int a, int b){
if(b==0){
return a;}
else{
return f(a,(b-1))-f(a/2,(b-1));}
}```

5. what is MainCL , i never heard of it.
is it just like int main()?

6. Wish instructors did not do braindead things like #define MainCL ...

As far as recursion, it is easy to do in C, you need 2 things:
2. stopping condition to unwind your recursion

Also you don't want to recurse too deep, every call to itself takes up stack space in a form of return address and parameters, after so many calls you may run out of stack space, but that's just some technical detail.

Code:
```#include "stdio.h"

double factorial(double a)
{
/* Stopping condition */
if (a < 1.0)
return 1.0;

/* algorithm based on itself */
return a * factorial(a-1.0);
}

int main(int argc, char **argv)
{
printf("factorial(5)=%f", factorial(5.0));

return 0;
}```