×

Java Programs

Java Practice

Java program to convert a decimal number to its octal equivalent using recursion

Given a decimal number, we have to convert it to its octal equivalent using recursion.
Submitted by Nidhi, on June 03, 2022

Problem statement

In this program, we will read an integer number from the user, and then we will convert it to an equivalent octal number using recursion.

Java program to convert a decimal number to its octal equivalent using recursion

The source code to convert a decimal number to its octal equivalent using recursion is given below. The given program is compiled and executed successfully.

// Java program to convert a decimal number to its 
// octal equivalent number using the recursion

import java.util.*;

public class Main {
  static int tmp = 1;
  static int oct = 0;

  public static int decToOct(int num) {
    if (num != 0) {
      oct = oct + (num % 8) * tmp;
      tmp = tmp * 10;
      decToOct(num / 8);
    }
    return oct;
  }

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

    int num = 0;
    int res = 0;

    System.out.printf("Enter number: ");
    num = X.nextInt();

    res = decToOct(num);
    System.out.printf("Octal number is: " + res);
  }
}

Output

Enter number: 134 
Octal number is: 206

Explanation

In the above program, we imported the "java.util.*" package to use the Scanner class. Here, we created a public class Main. The Main class contains two static methods decToOct() and main(). The decToOct() is a recursive method that converts a decimal number into an octal number and returns the result to the calling method.

The main() method is the entry point for the program. Here, we read two integer numbers from the user and called decToOct() method to convert the decimal number to octal and printed the result.

Java Recursion Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.