1. Home
  2. Computing & Technology
  3. Java
photo of Paul Leahy
Paul's Java Blog

By Paul Leahy, About.com Guide to Java

Monday's Programming Question

Sunday October 26, 2008

This week it felt like it was 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 1. 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.

So, this week 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

Hint: The method will take a starting String value of "OOOOOOOOOX", print the String to the screen, modify the String and then call itself with the new String value.

Comments
October 28, 2008 at 1:50 am
(1) Jose Ayerdis says:

Long time without posting i’ve been busy thanks for keeping me on program shape
A matter of five minutes ok?
public class ChallengeTest{

public static String recursiveMethod(String chain){
System.out.println(chain);
if(chain.equals(”OXXXXXXXXX”)){
return chain;
}else{
return recursiveMethod( chain.replace(”OX”,”XX” ));
}
}

public static void main(String… args){
recursiveMethod(”OOOOOOOOOX”);
}
}

October 31, 2008 at 8:19 pm
(2) Paul Leahy says:

glad to see you back, good stuff on the program :)

Leave a Comment

Line and paragraph breaks are automatic. Some HTML allowed: <a href="" title="">, <b>, <i>, <strike>

Discuss
Community Forum
Explore Java
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Java

©2009 About.com, a part of The New York Times Company.

All rights reserved.