×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang program to calculate the sum of all digits of a given number using recursion

Here, we are going to learn how to calculate the sum of all digits of a given number using recursion in Golang (Go Language)?
Submitted by Nidhi, on March 12, 2021 [Last updated : March 03, 2023]

Sum of all digits of a number using recursion in Golang

Problem Solution:

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.

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.

Golang code to find the sum of all digits of a number using recursion

// 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.

Golang Recursion Programs »





Comments and Discussions!

Load comments ↻





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