Java Program to Convert a Decimal Number to Its Octal Equivalent Using Recursion

You are currently viewing Java Program to Convert a Decimal Number to Its Octal Equivalent Using Recursion

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

// 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

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply