+ 1
how to solve
Calculating the sum of a number is a popular programming request. A number is given as input, calculate and output the sum of its digits. Example Input Data: 426 Sample Output Data: 12 Hint: use a while loop to iterate over the number. During each iteration, add the last digit to the sum to get the remainder by 10 (number% 10), then remove the last digit of the number by dividing it by 10 (number / 10). fun main(args: Array<String>) { var num = readLine()!!.toInt() // var num=426 var i=12 while(i<=num) var sum=(num%10) println(sum) }
5 Réponses
+ 1
//Where you not understanding there?
//the total code время Ч
fun main(args: Array<String>) {
var num = readLine()!!.toInt() //for taking input
var sum=0 //declare before loop
while (num>0) //**using a while loop to iterate over the number until number>0 (no more digits to add)
{
//**During each iteration, add the last digit to the sum to get the remainder by 10 (number% 10)
sum = sum+(num%10); //add reminder to sum
//then remove the last digit of the number by dividing it by 10 (number / 10).
num = num/10
}
println(sum) //printing calculated sum.
}
+ 1
thanks
0
var sum=0 //declare before loop
while (num>0)
{
sum = sum+(num%10); //add reminder
num = num/10
}
println(sum)
0
can you explain, i want to understand
0
You're welcome..