Go Program to find Generic Root of a Number

Write a Go Program to find the generic root of a Number using For loop. The generic root of a number is the sum of all digits until the sum is less than 10. For instance, generic root of 98 = 9 + 8 = 17 => 1 + 7 = 8. To achieve this, we used nested for loop (for sum = 0; genNumber > 0; genNumber = genNumber / 10) to find the sum of digits. And the if else statement (if sum >= 10) to check the sum greater than or equal to ten further divides the value.

package main

import "fmt"

func main() {

    var genNumber, sum, remainder int

    fmt.Print("Enter the Number to find Generic Root = ")
    fmt.Scanln(&genNumber)

    for genNumber >= 10 {
        for sum = 0; genNumber > 0; genNumber = genNumber / 10 {
            remainder = genNumber % 10
            sum = sum + remainder
        }
        if sum >= 10 {
            genNumber = sum
        } else {
            fmt.Println("The Generic Root of this Number = ", sum)
        }
    }
}
Go Program to find Generic Root of a Number

Go Program to find Generic Root of a Number using Functions

In this Golang program, we created a (func digitSum(genNumber int)) function that returns the generic root of a given number.

package main

import "fmt"

func digitSum(genNumber int) int {
    var sum, remainder int
    for sum = 0; genNumber > 0; genNumber = genNumber / 10 {
        remainder = genNumber % 10
        sum = sum + remainder
    }
    return sum
}
func main() {

    var genNumber, sum int

    fmt.Print("Enter the Number to find Generic Root = ")
    fmt.Scanln(&genNumber)

    for genNumber >= 10 {
        sum = digitSum(genNumber)
        if sum >= 10 {
            genNumber = sum
        } else {
            fmt.Println("The Generic Root of this Number = ", sum)
            break
        }
    }
}
SureshMac:Goexamples suresh$ go run genericRoot2.go
Enter the Number to find Generic Root = 7346
The Generic Root of this Number =  2
SureshMac:Goexamples suresh$ go run genericRoot2.go
Enter the Number to find Generic Root = 932784
The Generic Root of this Number =  6