Given a Decimal Number as Input. Now, write a Kotlin Program to Convert Decimal Number to equivalent octal number.
Input: 4 Output: 4
Input: 213 Output: 325
Input: 423423 Output: 1472777
1. Program to Convert Decimal to Octal
Sourcecode –
import java.util.* import kotlin.math.pow fun main() { val read = Scanner(System.`in`) println("Enter n:") var decimalN = read.nextInt() var octalN = 0 var count = 0 while (decimalN != 0) { val rem = decimalN % 8 val c = 10.toDouble().pow(count) octalN += (rem * c).toInt() decimalN /= 8 count++ } println("Equivalent Octal: $octalN") }
When you run the program, output will be –
Enter n: 8 Equivalent Octal: 10
Explanation:
Here, we have created an object of Scanner. Scanner takes an argument which says where to take input from.
System.`in` means take input from standard input – Keyboard.
read.nextInt() means read anything entered by user before space or line break from standard input – Keyboard.
We stored value entered by user in variable decimalN.
Example,
Assume decimalN = 10
-
At decimalN = 10
Inside while loop,
rem = 2
c = 1
octalN = 2Now, decimalN = 1
count = 1 -
At decimalN = 1
Inside while loop,
rem = 1
c = 10
octalN = 12Now, decimalN = 0
count = 2 - At decimalN = 0 , (decimalN != 0) is false. So, while loop is terminated.
Finally, value in octalN is our resultant octal number for decimal number 10.
Note – It won’t work for large decimal number. If you want to convert large number you need to change data type in above code.
Or, you can use inbuilt library function to convert decimal to octal.
2. Using toOctalString() function to Convert Decimal to Octal
We can use Integer.toOctalString() function to convert decimal to octal number.
import java.util.* fun main() { val read = Scanner(System.`in`) println("Enter n:") val decimalN = read.nextInt() val octalResult = Integer.toOctalString(decimalN) println("Equivalent Octal: $octalResult") }
When you run the program, output will be –
Enter n: 100 Equivalent Octal: 144
Thus, we went through kotlin program to convert decimal number to octal number.