CS2
Recursion
14
Anagram Method
public void anagram( String prefix, String suffix )
{
String newPrefix, newSuffix;
int numOfChars = suffix.length();
if (numOfChars == 1) {
//End case: print out one anagram
outputBox.printLine( prefix + suffix );
}
else {
for (int i = 1; i <= numOfChars; i++ ) {
newSuffix = suffix.substring(1, numOfChars);
newPrefix = prefix + suffix.charAt(0);
anagram( newPrefix, newSuffix ); //recursion
//rotate left to create a rearranged suffix
suffix = newSuffix + suffix.charAt(0);
}
}
}
End case
Test
Recursive case
In pseudocode the above method is expressed as follows:

public void directoryListing( File dir )
{
   //assumption: dir represents a directory
   fileList = an array of names of files and
         subdirectories in the directory dir;

   for (each element in fileList) {
     if (an element is a file) {
       output the element’s filename;  //end case: it’s                            //a file.
     }
     else { //recursive case: it’s a directory
       call directoryListing with element as an argument;
      }
   }
}