Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a complete recursive java program to compute the heights of the tick marks

ID: 3630635 • Letter: W

Question

Write a complete recursive java program to compute the heights of the tick marks on a ruler. Assume that the length of the ruler is a power of 2 (say L=2^n, where n >=1) , and the marks are to be placed at every point between 0 and 2^n, not including the endpoints. The endpoints 0 and 2^n will have height 0. Here are the rules for computing the heights of the ticks for a ruler of length L=2^n:
1. The middle point of the ruler has height log(L), where the logarithm is base 2. Stop if L <= 2.
2. Break the ruler into two equal halves of length L/2 each and set L=L/2
3. Repeat step 1 for both halves resulting from step 2.
You may use an array of the appropriate size to hold the heights. When printing your output, print the heights on one line, and the position of the points below. For the printing of the positions of the points, just print the last digit of the position. Here is an example for n=8.

012131210
012345678

Here is an example for n=16.

01213121412131210
01234567890123456

Your program should prompt the user for an integer, check to make sure the length entered by the user is a power of 2 and at least 2. To check if a number is a power of 2, you need the Math.log and Math.round methods. Be careful that the Math.log routine in Java is base e (not base 2). You will need to do the appropriate conversion between base 2 and base e. Finally, your program should print the heights of the ruler's points as illustrated above.

Explanation / Answer

public static void fun(int l)
{
// 1. The middle point of the ruler has height log(L), where the logarithm is base 2. Stop if L <= 2.
// actually stop when L is 1, so we can print 1
if(l < 2)
return;
// 2. Break the ruler into two equal halves of length L/2 each and set L=L/2
int l2 = l/2;
// 3. Repeat step 1 for both halves resulting from step 2.
fun(l2);
// print this tick mark
// For the printing of the positions of the points, just print the last digit of the position.
System.out.print(((int)(Math.log(l)/Math.log(2)))%10);
// print upper tick marks
fun(l2);
}

public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);

System.out.print("Enter L: ");

int l = kb.nextInt();

// check if l is a power of 2
if(Math.log(l)/Math.log(2) == Math.floor(Math.log(l)/Math.log(2)))
{
// print 0 marks at either side
System.out.print("0");
fun(l);
System.out.print("0");
System.out.println();
// now print scale
for(int i = 0; i <= l; i++)
System.out.print(i%10);
System.out.println();
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote