Saturday, January 10, 2009

Recursion - Navarra

Our Christmas vacation is over. It is already a new year, thus we are entering a new lesson. It is not totally new because it is still programming but the lesson is harder than our past lessons. Last time, we discuss only the different conditions but now, we are focusing on a program that consist two or more functions aside from the main function. Isn’t in difficult???

Well, we have no choice but the study and remember the lessons that are being discussed to us because all of us want to pass this subject.


RECURSION is:

  • The repetitive process by which a functions calls itself is called recursion or circular definition.
  • This is a way of defining something in terms of itself.
  • A function is said to be recursive if a statement in the body of the function calls the function that contains it.

Recursion also has its parts. And that are:

Base Case

- This is the part of the recursive function that is found on the if clause. This contains the condition that should be satisfied at one point of execution to terminate the repetitive process done by the recursive function.


General Case

-This is the part of the recursive function that is found on the else-clause. This contains the function call of the recursive function to itself.


There is also two kind of recursion. Those are the Direct and Indirect Recursio

  • Direct Recursions are recursive functions that can call itself through a function call directly inside the body of the function.
  • v Indirect recursions are recursive functions that can call another functions outside its function.

EXAMPLES:

1.

factorial (int n)

{

if (n == 1 || n == 0) return 1;

else return (n * factorial (n-1));

}

Simplifying the expression……

4 * (factorial (4-1) = 24 general case

3 * (factorial (3-1) = 6 general case

2 * (factorial (2-1) = 2 general case

1 base case

Therefore, the final return value when n=4 is 24.

2.

Give the output of the ff. program when the value entered for a=5.

#include

main()

{

int a, b;

clrscr();

printf(“Enter a value:”);

scanf(“%d”, &a);

b= solve (a);

printf(“The new value is %d”, b);

getch();

}

solve (int a)

{
if (a = = 1) return 2;

else return (solve (a-1) + 2);

}

The output is 10.

No comments: