Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

method of defining functions in which the function being defined is applied within its own definition

is an important and powerful tool in problem solving and programming can be used as an alternative to iteration(looping)

a function is called recursive if a statement within body of that function calls the same function
a function that calls itself

ReturnType Function( Pass appropriate arguments ) {

if a simple case //base case or terminating condition solve it else call function with simpler version of problem
}

int multiply(int x, int y) { int ans;


if(y==1) ans = x; //simple case else ans = x + multiply(x, y-1); return ans;

multiply(6,3)

18
x is 6 y is 3 3 == 1 is false ans is 6 + mulitply(6,2) return (ans)

12

x is 6 y is 2 2 == 1 is false ans is 6 + mulitply(6,1) return (ans)

x is 6 y is 1 1 == 1 is true ans is 6 return (ans)

Given the mathematical function for computing the factorial: n! = n * (n - 1)!


Why this is a recursive function?

To compute n! we are required to compute (n - 1)!

We are also given the simple case. We define mathematically 0! 0! = 1


To understand factorial in a recursive sense, consider a few simple cases: 1! = 1 * 0! = 1 * 1 = 1 2! = 2 * 1! = 2 * 1 = 2 3! = 3 * 2! = 3 * 2 = 6

int factorial(int x) { int ans;


if(x == 0) ans = 1; else ans = x * factorial(x-1); return ans;

int factorial(int x) //a recursive function { int ans; if(x == 0) ans = 1; else

ans = x * factorial(x-1);
return ans;

}
int main() {

int num, result;


printf("Compute for the factorial of> "); scanf("%d", &num);

result = factorial(num);
printf("The factorial of %d is %d",num, result); return 0; }

Define a recursive function for Addition and Division

You might also like