Write a static method called printPowersOfTwo that takes an integer n as its onl
ID: 3631555 • Letter: W
Question
Write a static method called printPowersOfTwo that takes an integer n as its only parameter and prints the first n powers of two, separated by commas. For example, printPowersOfTwo(5) should print1, 2, 4, 8, 16
The method should print nothing if the parameter n is less than or equal to 0.
Notes:
Your method will need to perform n repetitions. This should help you to select which type of loop to use.
In computing the powers of two, your method should not use any methods from the Math class. Instead, the method should compute the powers of two itself. Hint: If you have one power of two, you can get the next power of two by multiplying by two! This is another example of a cumulative computation -- like the cumulative sum problems that we've seen in lecture.
You will need to use an if statement to decide whether a comma should be printed after a given number.
Don't forget that you can test the method that you write by using the Interactions Pane in DrJava. First enter the method definition itself (without the words "public static") at the command prompt in the Interactions Pane, and then enter method calls that use the method.
Explanation / Answer
public static void printPowersOfTwo(int n)
{
int currval = 1;
for(int i = 0; i < n; i++)
{
System.out.print(i);
// update currrent value
currval *= 2;
// print comma
if(i < n-1)
System.out.print(", ");
}
System.out.println();
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.