Steps to write Recursive methods / procedures

Step 1. Find and write the stopping condition

Step 2. Write the recursive part of the method

 

Another real life recursion Example:

Doing dishes:


 DoDishes{
        // Step 1.
	if (the sink is empty){
            do nothing;
        }
             
        else{ 
             // Step 2.              
              wash one dish;
             find somebody to doDishes;
       }            
 }


How to design a recursive method:

Use a solution to a smaller or easier version of the problem to arrive at the solution to your problem

Know when the problem is small enough to solve directly.

 

Write a recursive solution to the summation problem:

public int sum(int n){
     int result;
     if (n==1){
          result = 1;
     }
     else{
         result = n + sum(n-1);
     }
   return result;
}