How recursion works in java








Recursion

    Recursion is technique to call the method by itself.  This makes
    it is powerful to process some iterative task easily when it happens
    repetitively.  The below example clear the  recursion concept .


public class Recursionmethods {
           
           
            public  static  int  i=0;
           
              public static  int   mrc() {
                         
                              i++;
                         
                          if ( i<=9) {
                                      
                                        
                           System.out.println("mukesh"+i);                    
                         
                             mrc();
                            
                               }
                         
                         
                          return i;
                         
                         
                  }
           
            public static void main(String[] args) {
                        // TODO Auto-generated method stub

                       
                        int k =     mrc();
                                         
            System.out.println( k);
                       
            }

}

 Here  is  output of this program after running it . You  can the function
 call  itself   until  9  then it  return the value  of  variable I .

mukesh2
mukesh3
mukesh4
mukesh5
mukesh6
mukesh7
mukesh8
mukesh9
10


Another  example of    recursion is    factorial   of number   n .   Here   you
can  check the  code  of the  n factorial .



public class Facto {

           
           
           
            static int factorial(int n){     
       
                       
                         if(n>=2)
                         System.out.print( n +"*");
                         else
                          System.out.print(  +n);
                         
                       
                         
                          if (n == 1) {    
          return 1;     
             }
          else     
           
          {
              
          return(n * factorial(n-1)); 
           }
     
         
         }     

       public static void main(String[] args) { 
           
           
        System.out.println("");
        System.out.println("Factorial of 11 is: "+factorial(11)); 
     
       } 
           

    }


Program sample out put  of  factorial 11 is.


11*10*9*8*7*6*5*4*3*2*1Factorial of 11 is: 39916800





How recursion works in java How   recursion   works in java Reviewed by Mukesh Jha on 4:46 AM Rating: 5

No comments:

Add your comment

All Right Reserved To Mukesh Jha.. Theme images by Jason Morrow. Powered by Blogger.