/* ============================================================================ * File: Fibonacci.java * ---------------------------------------------------------------------------- * * This file is part of the Microsoft Supplemental UI Library for Visual J# .NET * Code Samples. * * Copyright (C) 2003 Microsoft Corporation. All rights reserved. * * THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, * WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. * ============================================================================ */ package RecursionDemo; /** * This class implements RecursiveFunction interface to demonstrate calculation of * Fibonacci numbers as recursive funtion. * Refer Factorial.java also. */ public class Fibonacci implements RecursiveFunction { private RecursionStack stack; public String getName() { return "Fibonacci Function"; } public String getDescription() { return "This function generates Fibonacci numbers." + " Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, ..." + " i.e. the next number is sum of previous two numbers."; } public String getCode() { return "public int fibonacci(int n) {\n" + " if (n <= 1)\n" + " return 0;\n" + " else if (n == 2)\n" + " return 1;\n" + " else\n" + " return (fibonacci(n - 1) + fibonacci(n - 2));\n" + "}"; } public int doRecursion(int n) { stack.push(n); int retVal; if (n <= 1) { retVal = 0; } else if (n == 2) { retVal = 1; } else { retVal = doRecursion(n - 2) + doRecursion(n - 1); } stack.pop(retVal); return retVal; } public void setRecursionStack(RecursionStack s) { stack = s; } }