|
|
|
|
Top Topics in our Forum';
|
|
Warning: include(/home/mathwa6/public_html/php_include/forum_left_side.php) [function.include]: failed to open stream: No such file or directory in /home/mathwa6/public_html/php_include/ontheLeft_moris.php on line 296 Warning: include() [function.include]: Failed opening '/home/mathwa6/public_html/php_include/forum_left_side.php' for inclusion (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/mathwa6/public_html/php_include/ontheLeft_moris.php on line 296 |
Recursion Examples in javaRecursion ClassBelow is part of a class I named Recursion. What will be the output of running this code? (If you've never studied recursion, you will probably be surprised.) Example Recursion in Java #1
public class Recursion {
public int getNthFibonacci( int n )
{
if ( n == 1 || n == 2 )
return 1;
else
return getNthFibonacci( n-1 ) + getNthFibonacci( n-2 );
}
public static void main(String[] args){
Recursion myRecursor = new Recursion();
System.out.println( myRecursor.getNthFibonacci(5) );
}
}
Reversing a String with Recursion
import java.util.Scanner;
public class StringRecursion{
public static void main (String[] args){
Scanner scan = new Scanner (System.in);
System.out.println("Enter text to reverse: ");
String s = scan.nextLine();
reverseString(s);
}
public static void reverseString(String s){
if (s.length() <=1){
System.out.print(s);
}
else{
reverseString (s.substring(1, s.length()));
System.out.print(s.substring(0,1));
}
}
}
public class Recursion{
void countItDown( int counter)
{
if(counter == 0)
return;
else
{
System.out.println("Count : " + counter);
counter--;
countItDown(counter);
System.out.println(""+counter);
return;
}
}
public static void main(String[] args){
Recursion myRecursor = new Recursion();
myRecursor.countItDown(5);
}
}
The Output is shown below
Count : 5 Count : 4 Count : 3 Count : 2 Count : 1 0 1 2 3 4
|