Recursion Homework Help
When a Function calls itself during the course of program, it is said as Recursive Function. The best example is Factorial Function.
fact(x) = x*(x-1) *(x-2) *(x-3) *(x-4) *(x-5) *(x-6) ……. 3*2*1
or
We can define Factorial in Recursive way.
fact(x) = 1 , if x = 0
= x*fact(x-1) , if x>0
In the C Language,
int fact (int x)
{
{//} if (x = = 0)
return 1;
else
return x*fact(x-1);
}
In C we can divide Functions in five categories:
- Functions with no arguments and no return values.
- Functions with arguments and no return values.
- Functions with arguments and return values.
- Functions that return multiple values.
- Functions with no arguments and return values.
I’ll show you one example for each of these Functions:
1. void no_argument_no_return ( )
{
printf(“Hello!!”);
return;
}
2. void argument_no_return (int x)
{
printf(“The value of argument is: %d”,x);
return;
}
3. int argument_return (int a, int b)
{
int result;
result = a+b;
printf(“The sum of arguments is : %d”,result);
return result;
}
4. Function that returns multiple values:
This is a bit tricky, a Function cannot return multiple values but we can do that if we use the Function smartly. As we have seen that, we can use arguments to send values to the Function, similarly we can use arguments to retrieve values from the Function too.
This is can be done using pointer. We’ll see this when we’ll study pointer.
5. int no_argument_return ( )
{
int i;
i = 10;
return i;
}