Q:

Kotlin program to convert octal number to decimal number

belongs to collection: Kotlin Basic Programs

0

Given a number in octal number system format, we have to convert it into decimal number system format.

Example:

    Input:
    num = 344

    Output:
    228

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to convert octal number to decimal number in Kotlin

package com.includehelp.basic

import java.util.*

//Main function Entry Point of Program
fun main(arg: Array<String>) {
    //Input Stream
    val sc = Scanner(System.`in`)

    //Input Octal Number
    println("Enter Octal Number  : ")
    var octalNumber: Int = sc.nextInt()

    var decimalNumber=0
    var i = 0
    var isCorrectOctal=true;


    val octalStr = octalNumber.toString();
    //Check Given no is valid Ocatal Number or not
    for(i in octalStr.indices){
       if (octalStr[i] !in '0'..'7' ){
           isCorrectOctal=false
       }
    }

    if(isCorrectOctal){
        //Convert Octal to Decimal
        while (octalNumber > 0) {
            val r= octalNumber % 10
            decimalNumber += (r * Math.pow(8.0,i.toDouble())).toInt()
            octalNumber /= 10
            i ++
        }

        //Print Decimal Number
        println("Decimal: $decimalNumber")
    }else{
        System.err.println("Invalid Octal Number !!")
    }
}

Output

Run 1:
Enter Octal Number  :
344
Decimal: 228
-------
Run 2:
Enter Octal Number  :
48
Invalid Octal Number !!
-------
Run 3:
Enter Octal Number  :
47
Decimal: 39

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Kotlin Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Kotlin program to calculate the sum of natural num... >>
<< Kotlin program to convert octal number to binary n...