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

The following Java method converts a positive decimal integer to base 8 (octal)

ID: 3880661 • Letter: T

Question

The following Java method converts a positive decimal integer to base 8 (octal) and displays the result.
Explain how the function works and trace it on the input n=100.
static void displayOctal(int n){
if(n>0){
if(n/8>0){
displayOctal(n/8);
}
System.out.println(n%8);
}
}
7. Use what you learned in problem 6 above to create a recursive function called integerToString() that
returns a String representation of an integer n expressed in base b. For instance the function call
integerToString(100,8) would return the String “144”, which is what was printed in problem 6.
static String integerToString(int n, int b){
// your code starts here
// your code ends here
}

Explanation / Answer

Answer)

Question 7)

public class OctalProgram{

public static void main(String []args){
displayOctal(100); //calling method with value 100
}

static void displayOctal(int n){ // method defined and implemented to convert decimal to octal
if(n>0){ // n=100, so n>0, true | n=12, n> 0, true | n=0, false
if(n/8>0){ //n/8 = 12, so that's > 0 | 12/8 = 1 > 0, true
displayOctal(n/8); // calling displayOctal again with 100/8, calling displayOctal again with 1/8 = 0
}
System.out.println(n%8); // display 100%8 = 4 | 12%8 = 4 | 1%8 =1| reverse display = 1 4 4. Decimal to octal converted
}
}

}