recursion

6
A simple example of recursion would be: void recurse() { recurse(); //Function calls itself } int main() { recurse(); //Sets off the recursion } This program will not continue forever, however. The computer keeps function calls on a stack and once too many are called without ending, the program will crash. Why not write a program to see how many times the function is called before the program terminates? #include <iostream> using namespace std; void recurse ( int count ) // Each call gets its own count { cout<< count <<"\n"; // It is not necessary to increment count since each function's // variables are separate (so each count will be initialized one greater) recurse ( count + 1 ); } int main() { recurse ( 1 ); //First function call, so it starts at one } This simple program will show the number of times the recurse function has been called by initializing each individual function call's count variable one greater than it was previous by passing in count + 1. Keep in mind, it is not a function restarting itself, it is hundreds of functions that are each unfinished with the last one calling a new recurse function. It can be thought of like the Russian dolls that always have a smaller doll inside. Each doll calls another doll, and you can think of the size being a counter variable that is being decremented by one.

Upload: anish-chib

Post on 20-Jul-2016

5 views

Category:

Documents


1 download

DESCRIPTION

recursion tuts

TRANSCRIPT

Page 1: recursion

A simple example of recursion would be: void recurse(){ recurse(); //Function calls itself}

int main(){ recurse(); //Sets off the recursion}This program will not continue forever, however. The computer keeps function calls on a stack and once too many are called without ending, the program will crash. Why not write a program to see how many times the function is called before the program terminates? #include <iostream>

using namespace std;

void recurse ( int count ) // Each call gets its own count{ cout<< count <<"\n"; // It is not necessary to increment count since each function's // variables are separate (so each count will be initialized one greater) recurse ( count + 1 );}

int main(){ recurse ( 1 ); //First function call, so it starts at one }This simple program will show the number of times the recurse function has been called by initializing each individual function call's count variable one greater than it was previous by passing in count + 1. Keep in mind, it is not a function restarting itself, it is hundreds of functions that are each unfinished with the last one calling a new recurse function.

It can be thought of like the Russian dolls that always have a smaller doll inside. Each doll calls another doll, and you can think of the size being a counter variable that is being decremented by one.

Think of a really tiny doll, the size of a few atoms. You can't get any smaller than that, so there are no more dolls. Normally, a recursive function will have a variable that performs a similar action; one that controls when the function will finally exit. The condition where the function will not call itself is termed the base case of the function. Basically, it is an if-statement that checks some variable for a condition (such as a number being less than zero, or greater than some other number) and if that condition is true, it will not allow the function to call itself again. (Or, it could check if a certain condition is true and only then allow the function to call itself).

A quick example: void doll ( int size ){

Page 2: recursion

if ( size == 0 ) // No doll can be smaller than 1 atom (10^0==1) so doesn't call itself return; // Return does not have to return something, it can be used // to exit a function doll ( size - 1 ); // Decrements the size variable so the next doll will be smaller.}int main(){ doll ( 10 ); //Starts off with a large doll (it's a logarithmic scale)}This program ends when size equals one. This is a good base case, but if it is not properly set up, it is possible to have an base case that is always true (or always false).

Once a function has called itself, it will be ready to go to the next line after the call. It can still perform operations. One function you could write could print out the numbers 123456789987654321. How can you use recursion to write a function to do this? Simply have it keep incrementing a variable passed in, and then output the variable...twice, once before the function recurses, and once after... void printnum ( int begin ){ cout<< begin; if ( begin < 9 ) // The base case is when begin is greater than 9 { // for it will not recurse after the if-statement printnum ( begin + 1 ); } cout<< begin; // Outputs the second begin, after the program has // gone through and output}This function works because it will go through and print the numbers begin to 9, and then as each printnum function terminates it will continue printing the value of begin in each function from 9 to begin.

This is just the beginning of the usefulness of recursion. Here's a little challenge, use recursion to write a program that returns the factorial of any number greater than 0. (Factorial is number*number-1*number-2...*1).

Hint: Recursively find the factorial of the smaller numbers first, i.e., it takes a number, finds the factorial of the previous number, and multiplies the number times that factorial...have fun.

Page 3: recursion

Advantage :

Recursion is used to divide the problem into same problem of subtypes and hence replaces complex nesting code.

Disadvantage :

Recursion takes a lot of stack space, usually not considerable when the program is small and running on a PC.

It is very hard to debug or extend the functionality in case of recursive logic.

1. A recursive function is a function that calls itself.2. The speed of a recursive program is slower because of stack overheads.3. In recursive function we need to specify recursive conditions, terminating conditions,

and recursive expressions.4. see recursion means a function calls repeatedly

It uses system stack to accomplish it's task....as stack uses last in last out approachand when a function is called the controlled is moved to where function is defined which has it is stored in memory with some address this address is stored in stack

second recursion is very interesting ....it reduces a time complexity of a program for egsay you have created a program for mergesort which uses recursion ie divide and conquer approach and insertion sort which uses normal programmingnow from time complexity point of view you will choose only merge sort to sort a arrayas it has time complexity of nlognand insertion sort has n*n2:-it haS disadvantage alsoit involves a lot of memory wastageand very much typical concept to understand

5.Before each recursive calls current values of the varibles

6.in the function is stored in the PCB, ie process control

7.block and this PCB is pushed in the OS Stack. 8.So sometimes alot of free memory is require for

recursive9.solutions.10.

Page 4: recursion

11. Remember : whatever could be done through recursion could be

12. done through iterative way but reverse is not true.

13.14. #include <stdio.h>

int add(int k,int m);

main(){    int k ,i,m;    m=2;    k=3;    i=add(k,m);    printf("The value of addition is %d\n",i);}

int add(int pk,int pm){    if(pm==0)       return(pk);    else       return(1+add(pk,pm-1));}

double power(double x, int n);

int main() {  double x = 0.0;  int n = 0;  for(x = 2.0 ; x<= 5.0; x += 0.5)    for(n = 0 ; n<5 ; n++)      printf("%.2lf raised to the power %d = %.2lf\n", x, n, power(x,n));}

/* Function to raise x to the power n.*/double power(double x, int n) {  if(n == 0)    return 1.0;  else    return x * power( x , n - 1 );}

           #include <stdio.h>

long fibonacci( long n ); 

int main(){   long result;    long number; 

   printf( "Enter an integer: " );   scanf( "%ld", &number );

   result = fibonacci( number );

Page 5: recursion

   printf( "Fibonacci( %ld ) = %ld\n", number, result );      return 0;

}

long fibonacci( long n ){   if ( n == 0 || n == 1 ) {      return n;   }    else {       return fibonacci( n - 1 ) + fibonacci( n - 2 );   }    }