Fibonacci Calling Sequence
The example demonstrate the idea behind how the recursion is done in the Fibonacci sequence
/* * Recursion keep tracks of fibonacci */ import java.util.*; public class TestRecursion { static int call=0; static int completed= 0; static Stack stack = new Stack(); static Stack stack2 = new Stack(); public static int f(int n) { call++; System.out.println("The call number = " + call + " for n = " + n + " has been issued" ); System.out.println(); if ((n==0)|| (n==1)) { completed ++; System.out.println("The call number = " + call + " for n = " + n + " has been completed and its completion # = " + completed ); System.out.println("The return value of this call = " + 1); System.out.println(); return 1; } System.out.println(); stack2.push(call); int result1 = f(n-1); stack.push(n); int result2 = f(n-2); completed++; System.out.println("The call number = " + stack2.pop() + " for n = " + stack.pop() + " has been completed and its completion # = " + completed ); System.out.println( " The return value = " + ( result1 + result2)); System.out.println(); return result1 + result2; } public static void main(String[] args) { int n= 5; System.out.println(f(n)); } }
< Java > <Home>< Java Programs >