Recursive programming


Recursive programming in .net

When one method calls same method, usually with small number of arguments is called recursion. Alternative to recursive programming is through stack programming. Even some recursions can be solved using looping like factorial number etc. Stack is a data structure based on LIFO( Last in first out) manner.

Ex:- items:- 10,20,30,40

Above items are arranged as below in stack

40 top
30
20
10 bottom

Whenever item is deleted , it is deleted from top ie 40 and Now stack has values 10,20,30

Whenever item is added , it is added on top ie 50 added on Top, now stack becomes 10,20,30,50.

In order to write logic for recursive programming , then write based on stack working principle as said above.

Ex:-

Let take function sum(5) calculates the total value from 1 to 5.
When you decrease one value in sum(5) , you will get sum(4).
Similary sum(3), sum(2),sum(1) etc.

Ie
Stack like below
Sum(1)
2+Sum(2)
3+Sum(3)
4+Sum(4)
5+sum(5)

On top of the stack sum(1) which returns value 1,Which is handed over to the sum(2) ie 2+sum(2) becomes 2+1=3

Now this 3 value is handed over to sum(3) function ie 3+sum(3) becomes 3+3 =6 which is handed over to sum(4)

Like this at last you will get 5+10=15

So sum of 1 to 5 values is 15.

int sum(int n)
{
If(n= = 1)
Return 1;
Else
n+sum(n-1);
}

Using looping above function is rewritten as

int sum(int n)
{
int tot=0;
for(int i=n;i>0;i--)
tot=tot+i;

return tot; // returns total value
}

Using stack above functions are rewritten as

int sum(int n)
{
Stack s=new Stack();
For(int i=1;i {
s.push(i);

}
Int tot=0;

While(s.IsEmpty)
{
Tot=tot+(int) s.pop();
}
Return tot;
}

To write recursion, you require more problem solving skills
and based on stack behavior , you can write logic for recursion.


Attachments

  • Recursive programming (38477-2308-Recursive-programming.pdf)
  • Comments

    No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: