Home > Software design >  Why doesn't this While loop work as intended?
Why doesn't this While loop work as intended?

Time:10-16

Hey guys, newbie here. One question, can't understand why this while loop doesn't work even when I entered a int bigger than 9 to the variable num, the while loop should repeat itself until the expression is false, and it doesn't, no output even. Am I missing something here? Thanks in advance.

fun main () {
    
    while(true) {
    println ("\nWrite a positive number: ")
    var num = readLine()!!.toInt()
    var sum = 0
    if (num > 9) {
        while (num > 9) {
            var digit = num % 10
            sum = sum   digit
            num = num / 10
        }
        println("\nDigit Sum: $sum")

    } else if (num in 1..9) {
        println("\nDigit Sum for the number $num is $num")
    } else {
        println("\nInvalid input, try again.")
    } 

}

}

CodePudding user response:

You don't need to redeclare the variables every time

var sum = sum   digit
var num = num / 10

So simply remove var

sum = sum   digit
num = num / 10

CodePudding user response:

The issue is that you are not summing the last num when it gets less or equal to 9. You can even simplify your code a bit. Try the following:

fun main() {
    while(true) {
        println ("\nWrite a positive number: ")
        val insertedNumber = readLine()!!.toInt()
        var num = insertedNumber
        var sum = 0
        while (num > 9) {
            val digit = num % 10
            sum = sum   digit
            num = num / 10
        }
        sum = sum   num
        println("\nDigit Sum for the number $insertedNumber is $sum")
    }
}
  • Related