Kotlin program to find sum of digits of a number

Kotlin | Sum of digits of a number: Here, we are going to learn how to find the sum of all digits of a given number in Kotlin programming language? Submitted by IncludeHelp, on April 20, 2020

Problem statement

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

Example

Input:
Number: 12345

Output:
Sum: 15

Kotlin - Find sum of digits of a number

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

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

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.