# Kotlin Program to Convert Octal Number to Decimal

###### Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners. Also, if you are interested in content writing, you can mail us at tutorialwing@gmail.com.

Given an octal number as input. Now, write a Kotlin program to convert Octal number to Decimal Number.

```Input:
20

Output:
16
```
```Input:
324

Output:
212
```
```Input:
1000

Output:
512
```

## 1. Program to Convert Octal to Decimal

###### Pseudo Algorithm
• Initialise a variable decimalNum, that stores equivalent decimal value, with 0
• Extract each digit from the octal number.
• While extracting, multiply the extracted digit with proper base (power of 8).
• For example, if octal number is 110, decimalNum = 1 * (8^2) + 1 * (8^1) + 0 * (8^0) = 72

Sourcecode –

```import java.util.*

fun main() {

println("Enter n:")

var decimalNum: Long = 0
if(checkOctalNumber(octalN)) {
var n = octalN

var base = 1
while (n != 0.toLong()) {
val lastDigit = n % 10
n /= 10
decimalNum += lastDigit * base
base *= 8
}
println("Equivalent Decimal : \$decimalNum")
} else {
println("\$octalN is not a octal number")
}
}

private fun checkOctalNumber(octalNum: Long): Boolean {
var isOctal = true

var n = octalNum
while (n != 0.toLong()) {
val lastDigit = n % 10
if(!((lastDigit >= 0.toLong()) || (lastDigit <= 7.toLong()))) {
isOctal = false
break
}
n /= 10
}
return isOctal
}
```

When you run the program, output will be –

```Enter n:
2432
Equivalent Decimal : 1306
```
###### 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.nextLong() means read anything entered by user before space or line break from standard input – Keyboard.

We stored value entered by user in variable octalN.

At first, we checked if entered value is octal or not.
If NO, we print a message ” number is not octal number”.

• We use checkOctalNumber function to check if number is octal or not. If any digit in number is neither 0 nor 1, then, it is not octal number.

If Yes, we start converting those number into decimal –

• variable base contains power of 8 to the position at which current last digit we have in lastDigit
• Decimal value is sum of lastDigit * (power of 8 to the position at which current lastDigit is at)
• For example,
octalN = 110

decimalN = 1 * (8 ^ 2) + 1 * (8^1) + 0 * (8 ^ 0) = 72

Thus, we went through Kotlin Program to Convert Octal Number to Decimal Number.