Top Topics in our Forum';
Math Video Game! Play Fraction Balls!

A+    A−    B  
Algebra
Games
Geometry
Interactive
Trigonometry
Forum




AddThis Social Bookmark Button

Recursion Examples in java

Recursion Class

Below 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


The recursive function below will produce the nth Fibonacci number.
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


Top
Welcome Guest
Please Log in or register
Who's online: 7 Guests, 0 Users :        Please welcome krystirooks, our newest member.
AddThis Social Bookmark Button Page copy protected against web site content infringement by Copyscape