In this program, we will create a recursive function to calculate the sum of all digits of the specified number and return the result to the calling function.
The source code to calculate the sum of all digits of a given number using recursion is given below. The given program is compiled and executed successfully.
// Golang program to calculate the sum of all digits
// of a given number using recursion
package main
import "fmt"
var sum int = 0
func SumOfDigits(num int) int {
if num > 0 {
sum += (num % 10) //add digit into sum
SumOfDigits(num / 10)
}
return sum
}
func main() {
var num int = 0
var result int = 0
fmt.Printf("Enter number: ")
fmt.Scanf("%d", &num)
result = SumOfDigits(num)
fmt.Printf("Sum of digits is: %d\n", result)
}
Output:
Enter number: 3624
Sum of digits is: 15
Explanation:
In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package that includes the files of package fmt then we can use a function related to the fmt package.
var sum int=0
func SumOfDigits(num int)int{
if(num>0){
sum+=(num%10); //add digit into sum
SumOfDigits(num/10);
}
return sum;
}
In the above code, we created a global variable sum with the initial value 0, and we implemented a recursive function SumOfDigits() that accepts a number and returns the sum of all digits to the calling function.
In the main() function, we read an integer number from the user and sum of all digits of the specified number using recursive function SumOfDigits() and printed the result on the console screen.
Program/Source Code:
The source code to calculate the sum of all digits of a given number using recursion is given below. The given program is compiled and executed successfully.
Output:
Explanation:
In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package that includes the files of package fmt then we can use a function related to the fmt package.
In the above code, we created a global variable sum with the initial value 0, and we implemented a recursive function SumOfDigits() that accepts a number and returns the sum of all digits to the calling function.
In the main() function, we read an integer number from the user and sum of all digits of the specified number using recursive function SumOfDigits() and printed the result on the console screen.
need an explanation for this answer? contact us directly to get an explanation for this answer