Q:

Kotlin program to find sum of digits of a number

belongs to collection: Kotlin Basic Programs

0

Given an integer number, we have to find the sum of all digits.

Example:

    Input:
    Number: 12345

    Output:
    Sum: 15

To find sum of all digits – we extract the digits and add them.

All Answers

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

Program to find sum of digits of a number in Kotlin

package com.includehelp.basic

import java.util.*

/* function to get sum of digits */
fun getSumOfDigits(number: Int): Int {
    var number = number
    var sum = 0
    while (number > 0) {
        val r = number % 10
        sum += r
        number /= 10
    }
    return sum
}

// Main Function , Entry Point of Program
fun main(arg: Array<String>) {
    val sc = Scanner(System.`in`)
    
    // Input Number
    println("Enter Number  : ")
    val num: Int = sc.nextInt()
    
    //Call Function to get sum of digits
    val sumOfDigits = getSumOfDigits(num)
    // Print sumOfDigits
    println("Sum of Digits : $sumOfDigits")  
}

Output

Run 1:
Enter Number  :
12345
Sum of Digits : 15
-------
Run 2:
Enter Number  :
453456
Sum of Digits : 27

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 find area of circle... >>
<< Kotlin program to count digits in an integer numbe...