Bitcoin

Bitcoin
Bitcoin

Recursion

The repeated application of a recursive procedure or definition. It is the process by which a class or a method calls itself.
The base case returns a value without making any subsequent recursive calls. It does this for one or more special input values for which the function can be evaluated without recursion

For factorial(), the base case is n = 1. The reduction step is the central part of a recursive function.


public class FactorialImplements{
         public static void main(String args[]){
         int i,fact=1;
         int number=5;//It is the number to calculate factorial.
         for(i=1;i<=number;i++){
              fact=fact*i;
         }
        System.out.println("Factorial of "+number+" is: "+fact);
}

In fibonacci series, next number is the sum of previous two numbers for example 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 etc. The first two numbers of fibonacci series are 0 and 1. There are two ways to write the fibonacci series program in javaFibonacci Serieswithout using recursion.

public class FibonacciSeries {
  // recursive declaration of method fibonacci
  public static long fibonacci(long number) {
    if ((number == 0) || (number == 1)) // base cases
      return number;
    else
      // recursion step
      return fibonacci(number - 1) + fibonacci(number - 2);
  }

  public static void main(String[] args) {
    for (int counter = 0; counter <= 10; counter++)
      System.out.printf("Fibonacci of %d is: %d\n", counter, fibonacci(counter));
  }
}

No comments:

Post a Comment

Facebook