1. Technology

Going Around and Around

By

Level: Beginner

Focus: Methods

Recursion Question

It's time to go around and around with a recursive program. I can't honestly remember a time when I've wanted to implement a recursive method, but it's useful to know that you can. Simply put, the process called recursion is where a method calls itself.

The classic example of recursion is a program that calculates factorials (i.e., 7x6x5x4x3x2x1 = 5040). If you're feeling frisky and don't want to use a simple loop, the recursive method below could be used:

 private static long factorial(long number )
 {
   if (number == 1)
   {
     return 1;
   }
   else 
   {
     //method calls itself with the number     //reduced by 1
     return number * factorial(number-1);
   }
 } 
 

Notice how the method will continue to call itself until the number reaches one. Once it does the pattern of recursion stops and all the calculations that are waiting to be returned are passed back up the chain of method calls. Finally, the recursive process is finished as the result is passed back to the original call in the main method.

Can you write a program that calls a recursive method to print the following pattern to the screen?

 OOOOOOOOOX
 OOOOOOOOXX
 OOOOOOOXXX
 OOOOOOXXXX
 OOOOOXXXXX
 OOOOXXXXXX
 OOOXXXXXXX
 OOXXXXXXXX
 OXXXXXXXXX
Requirements:
  • the method must accept a String value as a parameter.
  • the printing of the pattern must happen from the main method.

Hint: Think about the String value that must first be passed to the method, how the method modifies the String and at what point the method needs to stop calling itself.

To get the most out of this question try and figure out the answer before coming back to read the solution on the next page.

  1. About.com
  2. Technology
  3. Java
  4. Programming Exercises
  5. Beginner Level
  6. Going Around and Around

©2014 About.com. All rights reserved.