Discover the answers you need at Westonci.ca, a dynamic Q&A platform where knowledge is shared freely by a community of experts. Find reliable answers to your questions from a wide community of knowledgeable experts on our user-friendly Q&A platform. Join our Q&A platform to connect with experts dedicated to providing accurate answers to your questions in various fields.

Melissa wrote the following method in Java. It is designed to compute 2^n, but returns an incorrect result. In which line has she made a mistake?
public static int powerTwo(int n)
if (n == 1){
return 1;
} else {
return 2 + powerTwo(n-1);


Sagot :

tonb

Answer:

public static int powerTwo(int n) {

  if (n == 0){

     return 1;

  } else {

     return 2 * powerTwo(n-1);

  }

}

Explanation:

There are actually three mistakes:

  • 2⁰ = 1, so the end criterium of the recursion should be n==0
  • the + should be a *
  • various curly braces missing