GO Program to find sum of digits in a number

For a better understanding of this example, we always recommend you to learn the basic topics of Golang programming listed below:

How to find the sum of digits in a number

Sum of the digits of a given number can be obtained by adding the digits of the number. For example , if the number given is 324 then the digit sum is 3 + 2 + 4, which will give us 9.

How to find the sum of digits in a number in the GO Program

Here we are showing to find the sum of digits in a number in the Go language. Here variables num for holding the number for find the sum of digits, and other variable sum, rem for holding the result and remainder. Use the for loop for finding sum and remainder as rem=num and sum= sum+rem.

Syntax for for loop


for    initializer; condition;   incrementor {
}

Given below are the steps which are used in the Go program. 

ALGORITHM

STEP 1: Import the package fmt

STEP 2: Start function main()

STEP 3: Declare the variable num, sum, rem

STEP 4: Read the number num using fmt.Scanfln()

STEP 5:Find the sum of digits using for loop from sum=0 to num = num / 10

STEP 6: Within the loop find remainder as rem = num % 10 and sum as  sum = sum + rem

STEP 7: Print the result variable sum using fmt.Println()

 

GO Source Code

                                          package main

import "fmt"
func main() {

    var num, sum, rem int
    fmt.Print("Enter the number to find the sum of digits = ")
    fmt.Scanln(& num)

    for sum = 0; num > 0; num = num / 10 {
        rem = num % 10
        sum = sum + rem
    }
    fmt.Println("The Sum of Digits of this number = ", sum)
}
                                      

OUTPUT

Enter the number to find the sum of digits = 1524
The Sum of Digits of this number =  12