# Haskell Program to convert Decimal to Octal

We can convert the Decimal number to an Octal using the recursion and unfoldr function of Haskell.

Decimal to octal conversion is a process of converting a decimal (base-10) number to its equivalent representation in octal (base-8) numbering system.

In decimal numbering system, we use 10 digits (0 to 9) to represent a number. In octal numbering system, we use 8 digits (0 to 7) to represent a number. To convert a decimal number to its equivalent octal representation, we divide the decimal number by 8 repeatedly until the quotient becomes 0, and keep track of the remainders. The remainders, read from bottom to top, give us the octal representation of the decimal number.

## Algorithm

• Step 1 − The decimalToOctal function is defined using internal function

• Step 2 − Program execution will be started from main function. The main() function has whole control of the program. It is written as main = do. In the main function, the decimalToOctal function is called with the argument 42 and the result is printed to the console.

• Step 3 − The resultant octal number is printed to the console using ‘putStrLn’ statement after the function is called.

## Example 1

In this example, the two helper functions used, decimalToOctal and decimalToOctalHelper, to perform the conversion. The decimalToOctal function uses a tail-recursive approach, where the result is built up in a string acc that is passed as an argument to the decimalToOctalHelper function. The decimalToOctalHelper function divides the decimal number by 8 repeatedly until it becomes 0, and the remainder of these divisions are concatenated to form the octal representation.

module Main where

decimalToOctal :: Int -> String
decimalToOctal 0 = "0"
decimalToOctal n = decimalToOctalHelper n []

decimalToOctalHelper :: Int -> String -> String
decimalToOctalHelper 0 acc = acc
decimalToOctalHelper n acc = decimalToOctalHelper (n div 8) (show (n mod 8) ++ acc)

main :: IO ()
main = putStrLn (decimalToOctal 42)


## Output

52


## Example 2

In this example, a function decimalToOctal is defined that takes an integer x as input and returns its equivalent octal representation as a string. The main function sets decimal to 42, which is then passed to the decimalToOctal function to get the octal representation. Finally, the result is printed to the screen using putStrLn.

import Data.List (unfoldr)

decimalToOctal :: Int -> String
decimalToOctal x = concat $reverse$ unfoldr step x
where step 0 = Nothing
step y = Just (show (y mod 8), y div 8)

main :: IO ()
main = do
let decimal = 42


## Output

The equivalent octal representation is: 052


## Conclusion

In Haskell, a decimal number is converted to octal using unfoldr function or by using recursion or tail-recursion.

Updated on: 06-Apr-2023

87 Views