Recursion
Recursion
Recursion
Previously we learned how method can call other methods.
However, Recursion method its a method that call itself.
There is two way to use recursion one directly and one with a helper.
if (n == 0)
return 1;
else
return n * factorial(n - 1);
Fibonacci series :
fib(0) = 0;
fib(1) = 1;
fib(index) = fib(index - 2) + fib(index - 1); index >= 2
import java.util.Scanner;
public class ComputeFibonacci {
/*
Find the smallest element in the list and swap it with the
first element
*/
public static void main(String[] args) {
int[] list = { 3, 4, 7, 2, 9 , 1 };
sort(list);
import java.io.File;
import java.util.Scanner;
CharacteTower of Hanoi
import java.util.Scanner;
public class TowerOfHanoi {
/** Main method */
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in); System.out.print("E
nter number of disks: ");
int n = input.nextInt();
else {
moveDisks(n - 1, fromTower, auxTower, toTower); System.out.
println("Move disk " + n + " from " +
fromTower + " to " + toTower);
moveDisks(n - 1, auxTower, toTower, fromTower);
}
}
}
//output//
Enter number of disks: 4
The moves are:
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
Move disk 4 from A to B
Move disk 1 from C to B
Move disk 2 from C to A
Move disk 1 from B to A
Move disk 3 from C to B
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
//Tail recursive
public class ComputeFactorialTailRecursion {
/** Return the factorial for a specified number */
public static long factorial(int n) {
return factorial(n, 1); // Call auxiliary method (invoke
}
Example:
import java.math.BigInteger;
import java.util.Scanner;
/**
* *18.1 (Factorial) Using the BigInteger class introduced
in Section 10.9, you can
* find the factorial for a large number (e.g., 100!).
* Implement the factorial method using recursion.
* Write a program that prompts the user to enter an intege
r and displays its factorial.
*/
if (runTest) {
System.out.println("Successful test indicator:
" + Test.testFactorial());
} else {
System.out.print("\nEnter an integer to find it
s factorial: ");
long numToFactor = in.nextLong();
}
}
/**
* 18.5 (Sum series) Write a recursive method to compute the fo
* m(i) = 1/3 + 2/5 + 3/7 + 4/9 + 5/11 + 6/13 + ...... + i/2i +
* <p>
* Write a test program that displays m(i) for i = 1, 2, . . .
*
* @author Harry D.
*/
public class Exercise18_05 {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
import java.util.Scanner;
/**
* *18.10 (Occurrences of a specified character in a strin
g) Write a recursive method that
* finds the number of occurrences of a specified letter in
a string using the following method header:
* public static int count(String str, char a)
* <p>
* For example, count("Welcome", 'e') returns 2.
* <p>
* Write a test program that prompts the user to enter a st
ring and a character, and displays the number of
* occurrences for the character in the string.
*/
public class Exercise18_10 {
}
}
import java.util.Scanner;
/**
* *18.17 (Occurrences of a specified character in an arra
y) Write a recursive method that
* finds the number of occurrences of a specified character
in an array. You need to
* define the following two methods. The second one is a re
cursive helper method.
/**
* *18.11 (Sum the digits in an integer using recursion) Wr
ite a recursive method that
* computes the sum of the digits in an integer. Use the fo
llowing method header:
* public static int sumDigits(long n)
* For example, sumDigits(234) returns 2 + 3 + 4 = 9.
* <p>
* Write a test program that prompts the user to enter an i
nteger and displays its sum.
* Section 18.5
*/
public class Exercise18_11 {
static int sum;
/**
* **18.12 (Print the characters in a string reversely) Rew
rite Programming Exercise 18.9
* using a helper method to pass the substring high index t
o the method. The
* helper method header is:
* public static void reverseDisplay(String value, int hig
h)
*/
public class Exercise18_12 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a String: ");
String s = in.next().trim();
reverseDisplay(s, s.length() - 1);
}
import java.util.Scanner;
/**
* *18.13 (Find the largest number in an array) Write a rec
ursive method that returns the
* largest integer in an array.
* <p>
* Write a test program that prompts the user to enter a li
import java.util.Scanner;
/**
* *18.14 (Find the number of uppercase letters in a strin
g)
* Write a recursive method to return the number of upperca
se letters in a string.
* <p>
* Write a test program that prompts the user to enter a st
import java.util.Scanner;
/**
* *18.16 (Find the number of uppercase letters in an arra
y) Write a recursive method
* to return the number of uppercase letters in an array of
characters. You need to
* define the following two methods. The second one is a re
cursive helper method.
* public static int count(char[] chars)
* public static int count(char[] chars, int high)
* Write a test program that prompts the user to enter a li
st of characters in one line
}
}
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.StrokeType;
/**
* 18.20 (Display circles) Write a Java program that displa
ys ovals,
* as shown in Figure 18.12b.
* <p>
* The circles are centered in the pane.
* <p>
* The gap between two adjacent circles is 10 pixels,
* and the gap between the border of the pane and the large
st
* circle is also 10.
*/
public class Exercise18_20 extends Application {
@Override
public void start(Stage primaryStage) {
RecursiveCirclePane circlePane = new RecursiveCircl
ePane();
Scene scene = new Scene(circlePane, 340, 340);
circlePane.widthProperty().addListener(cl -> circle
Pane.resetCircles());
circlePane.heightProperty().addListener(cl -> circl
ePane.resetCircles());
primaryStage.setScene(scene);
primaryStage.show();
circlePane.paint();
RecursiveCirclePane() {
import java.util.Scanner;
/**
* 18.21 (Decimal to binary) Write a recursive method that
converts a decimal number
* into a binary number as a string. The method header is:
* public static String dec2Bin(int value)
* Write a test program that prompts the user to enter a de
cimal number and displays its binary equivalent.
in.close();
}
import java.util.Scanner;
/**
* 18.22 (Decimal to hex) Write a recursive method that con
verts a decimal number into
* a hex number as a string. The method header is:
* public static String dec2Hex(int value)
* <p>
* <p>
* Write a test program that prompts the user to enter a de
cimal number and displays its hex equivalent
}
}
import java.io.File;
import java.util.Scanner;
/**
* 18.29 (Number of files in a directory) Write a program t
hat prompts the user to enter a
* directory and displays the number of the files in the di
rectory.
*/
public class Exercise18_29 {
}
}
return TOTAL_FILES;
}
}
import java.io.*;
/**
* 18.30 (Find words in all the files) Write a program that
finds all occurrences of a word in all the files
* under a directory, recursively.
* Pass the parameters from the command line as follows:
* <p>
* java Exercise18_30 dirName word
* For Example:
* cmd:>> javac Exercise18_30.java
* >>>>>> java Exercise18_30 ch_14 static
*/
public class Exercise18_30 {
static int occurrences = 0;
if (dir.isDirectory()) {
} else {
System.out.println("Please specify a Directory
for 'dirName'. ");
}
System.out.println("The word: \"" + word + "\" occu
rs " + occurrences + " times in: " + dir.getName());
if (files[fileIndex].isFile()) {
FileReader fileReader = new FileReader(files[fi
leIndex]);
BufferedReader bufferedReader = new BufferedRea
der(fileReader);
String line;
while ((line = bufferedReader.readLine()) != nu
ll) {
if (line.contains(word)) {
occurrences++;
}
}
}