There are n identical candies in a jar Each time you can tak

There are n identical candies in a jar. Each time you can take one or two candies from the jar. Write an iterative function in Java that calculates the number of ways in which you can eat the candies.

The Iterative Function is declared as follows:

int canIterative(int n) {

}

Examples:

Input: 0 Output: 1

Input: 5 Output: 8

Input: 2 Output : 2

Solution

Java functions:

   public static int factorial(int n)
   {
       if(n == 1 || n == 0)
       {
           return 1;
       }
       else
       {
       return n*factorial(n-1);  
       }
   }

   public static int canIterative(int n)
   {
   int ones = n;
   int twos = 0;
   int ways = 0;
   while(ones >= 0)
   {
       ways = ways + (factorial(ones + twos)/((factorial(ones))* (factorial(twos))));
       ones = ones - 2;
       twos = twos + 1;
   }

System.out.println(\"Number of ways = \" + ways);            
return ways;
   }

There are n identical candies in a jar. Each time you can take one or two candies from the jar. Write an iterative function in Java that calculates the number o

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site