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


This code is an implementation of decimal to octal conversion using recursion. The decimalToOctal method takes an integer dec as input and recursively converts it to its octal representation. The result is stored in a static variable oct which is initialized to 0 at the beginning of the program.

The method works by first checking if dec is not equal to 0. If it is not, it performs the following steps:

  • Calculate the remainder of dec when divided by 8.
  • Multiply the remainder obtained in step 1 by a temporary variable tmp which is initialized to 1. This is done to calculate the place value of the current octal digit.
  • Add the product obtained in step 2 to oct.
  • Multiply tmp by 10 to calculate the place value of the next octal digit.
  • Recursively call the decimalToOctal method with dec/8.

Finally, when dec becomes 0, the method returns the value of oct.

Source Code

import java.util.*;
public class DecToOct
{
	static int tmp = 1;
	static int oct = 0;
	public static void main(String[] args) 
	{
		Scanner input = new Scanner(System.in);
		System.out.printf("Enter the Decimal Number : ");
		int dec = input.nextInt();
		int octNum = decimalToOctal(dec);
		System.out.printf("Octal Number : " + octNum);
	}
	public static int decimalToOctal(int dec) 
	{
		if (dec != 0)
		{
			oct = oct + (dec % 8) * tmp;
			tmp = tmp * 10;
			decimalToOctal(dec / 8);
		}
		return oct;
	}
}
 

Output

Enter the Decimal Number : 18
Octal Number : 22