Question

Write a recursive method: public static int raise2ToN(int n) //computes and returns the value of 2n...

Write a recursive method:

public static int raise2ToN(int n)

//computes and returns the value of 2n using

//recursion.

Note: 2^3 = 2 * 2^2 .

2^2 = 2 * 2^1

2^1 = 2

What value/values of n will stop the recursion (base case)?

Sample output:

5

2 to 5 is 32

0 0
Add a comment Improve this question Transcribed image text
Answer #1

PROGRAM:

import java.util.*;
public class Main
{
   public static int raise2ToN(int n)
{
if(n==0)
{
return 1;
}
else
{
return 2*raise2ToN(n-1);
}
}

   public static void main(String[] args)
   {
       Scanner src=new Scanner(System.in);
       int num=0;
       System.out.print("Enter the value of n: ");
       num=src.nextInt();
       int res=raise2ToN(num);
       System.out.println("2 to "+num+" is "+res);
   }
}
OUTPUT:

This Programs contains a recursive method, which accepts the n value and calculate the 2n value .

In the method, we are continuously multiplying with 2 and decreasing the value of n until we reach the value of n as 0.

Hope this helps!!!

Add a comment
Know the answer?
Add Answer to:
Write a recursive method: public static int raise2ToN(int n) //computes and returns the value of 2n...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT