facebook like button

11 September, 2011

Recursion in C programming langauge

what is recursion?
  The word recursion bears meaning similar to self-repeating. In programming it can be useful for programmers. Recursion is mostly used when we work with series and linked lists. In mathematics you people may have seen recursion while working with series. There you might have encountered a problem in which n'th term of a series was given as a function of some previous term/terms and value of first term would be given. Let me remind you with examples. This is highly recommended that for you to go through the examples below and then proceed.

Example1:   A n'th term of a series is 1 more than the (n-1)th term. Find the 4th term of the series given that first term is 2.
   Solution: Given that. T(1)=2
      and T(n)=T(n-1) + 1;    ------>    Eq.-1   (n'th term as function of (n-1)th term)
      so T(4)=T(3) + 1;                       we'll write T(3) in terms of t(2)
           T(4)=T(2) + 1 + 1;               we'll write T(2) in terms of t(1)
           T(4)=T(1) + 1 + 1 + 1;         we'll write value of T(1)
           T(4)=2 + 1 + 1 + 1;
           T(4)=    Ans.
In this way you could find any term of the series.

Example2: Find the sum of first 5 natural numbers.
   Solution: If you know what natural numbers are, you'll know that
     It is given that nth term is n.
      S(1)=1      (Sum upto/of first term)
      and S(n)=S(n-1) + n;    (We got S(n) as a function of S(n-1))
             because this is obvious that
             sum up to n terms =  sum up to (n-1) terms + nth term.

      we have to find out
      so S(5)=S(4) + 5;                       we'll write S(4) in terms of S(3)
           S(5)=S(3) + 4 + 5;               we'll write S(3) in terms of S(2)
           S(5)=S(2) + 3 + 4 + 5;         we'll write S(2) in terms of S(1)
           S(5)=S(1) + 2 + 3 + 4 + 5;  we'll write value of S(1)
           S(5)=1 + 2 + 3 + 4 + 5;
           S(5)=15     Ans.
In this way you could find sum up to any term in the series.

That was mathematical recursion. In this case mathematical function used to express nth entity in terms of (n-1)th entity is called recursion function or recursive function.

Recursion in programming is same as mathematical recursion with a little bit programming touch. You have seen that a function can call other function to achieve any particular task. In programming when a function calls itself, its called recursion in programming jargon. As you'll practice programs, you'll get to know more. Next 2 programs will be for solving the 2 examples given above.

  In further posts we'll see how recursion can be used with linked lists and trees.
wait for it :P.

No comments:

Post a Comment

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply