Q:

Golang program to count digits of given number using recursion

belongs to collection: Golang Recursion Programs

0

In this program, we will create a recursive function to count the digits of the specified number and return the result to the calling function.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to count digits of a given number using recursion is given below. The given program is compiled and executed successfully.

// Golang program to count digits of given number
// using recursion

package main

import "fmt"

var count int = 0

//function to count digits
func CountDigits(num int) int {
	if num > 0 {
		count++
		CountDigits(num / 10)
	}
	return count
}

func main() {
	var num int = 0
	var result int = 0

	fmt.Printf("Enter number: ")
	fmt.Scanf("%d", &num)

	result = CountDigits(num)

	fmt.Printf("Count of digits is: %d\n", result)
}

Output:

Enter number: 3624
Count of digits is: 4

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 count int=0
//function to count digits
func CountDigits(num int)int{
    if(num>0){
        count++
        CountDigits(num/10);
    }
    return count;
}

In the above code, we created a global variable count with an initial value 0, and we implemented a recursive function CountDigits() that accepts a number and returns the count of digits to the calling function.

In the main() function, we read an integer number from the user and count digits of the number using recursive function CountDigits(), and printed the result on the console screen.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Golang program to calculate the sum of all digits ... >>
<< Golang program to calculate the power of a given n...