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

Write a program that uses recursion to convert a base 10 number into a base b nu

ID: 3669550 • Letter: W

Question

Write a program that uses recursion to convert a base 10 number into a base b number, where b < 10. If the number to be converted is n, then the algorithm to convert n to base b is:

Divide n by b. Store the quotient and the remainder.
The remainder is the rightmost digit of the final answer.
The quotient is now the new number n that you will recursively convert to base b.
Repeat step a by calling your recursive method with the quotient and the original base b.
Stop when n / b = 0. The remainder at this point will be the first digit of the final answer.

Explanation / Answer

import java.util.Scanner;

/**
* @author Srinivas Palli
*
*/
public class ConvertToBaseb {

   /**
   * @param args
   */
   public static void main(String[] args) {
       // TODO Auto-generated method stub
       Scanner scanner = null;
       try {

           int base;
           int number;

           scanner = new Scanner(System.in);
           System.out.print("Please enter the Number:");
           number = scanner.nextInt();
           System.out.print("Please enter the Base:");
           base = scanner.nextInt();
           // checking base <10
           if (base < 10) {
               System.out.println("RESULT:" + convert(number, base));
           } else {
               System.out.println("base should less than 10");
           }

       } catch (Exception e) {
           // TODO: handle exception
       } finally {
           scanner.close();

       }

   }

   /**
   * method to convert number to base
   *
   * @param number
   * @param base
   * @return
   */
   public static String convert(int number, int base) {
       int quotient = number / base;
       int remainder = number % base;

       if (quotient == 0) // base case
       {
           return Integer.toString(remainder);
       } else {
           return convert(quotient, base) + Integer.toString(remainder);
       }
   }

}

OUTPUT:
Please enter the Number:25
Please enter the Base:12
base should less than 10


Please enter the Number:24
Please enter the Base:4
RESULT:120

Please enter the Number:8
Please enter the Base:2
RESULT:1000

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