Sunday, July 27, 2014

recursion

General rule of recursion

1. instead of loop statement iteration, we manually do iteration by 

   calling the function again and again.

2. the purpose(ex. strcpy or strcmp done only one time in the base case)

3. have to carefully choose the else condition. otherwise that statement will be

executed in the all cases.

4. have to carefully put the return statment otherwise intended program will

return false vales.  

5. in recursion terminating statement can be in if case( that is return case)

   and calling the function itself can be in else case(which make loop) or vice versa depending on the requirement.

 


string length using iterative and recursion:


a1. strlen (without array length variable)
int strlen_r(char *s)
{
 if (*s=='\0') return 0;
 else return(1 + strlen_r(s+1));
} 
source: http://www.sparknotes.com/cs/recursion/examples/section1.rhtml

a2. strlen
int strlen(char *str,int len)
{
 if(str[len]=='\0')
return len;
else
 return strlen(str,++len);
* a2 using indexing operation and a1 is not using indexing operator
but have to check for integers called with this.



string comparison using ecursion:

a1. 

int strcmp_r(char *s, char *t)
{
 if (*s == '\0' || *s != *t) return *s - *t;
 else return(strcmp_r(s+1, t+1));
}
 
* very best and effective solution. superb above code!!! 
source: http://www.sparknotes.com/cs/recursion/examples/section1.rhtml 
 
a2. 
 

string copy using ecursion:

a1. recursive optimized approach:

char *strcpy_r(char *s, char *t)
{
 if ((*s = *t) != '\0') strcpy_r(s+1, t+1);
 return s;
}

* here reason for not giving the s in the else statement is, every time s will be returned.
  So in the first call of this function orignal 0th location memory of destination will be
  returned
 * and s++ is avoided and s + 1 given due.to not increment the original pointer
 
for more info refer the sourcee
source: http://www.sparknotes.com/cs/recursion/examples/section1.rhtml 

No comments:

Post a Comment