GO Program to find sum of digits in a number

How to find the sum of digits in a number

Here we are explaining how to find the sum of digits in a number in the Go program. We can use the built-in function fmt.println() to print anything and fmt.scanln() for reading the values. This function is defined under the fmt package and it helps to write standard output. In order to use these functions, we need to import the “fmt” package.

 

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

We are using fmt.println() function for printing the string to the output screen. 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. 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(#)

    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