Golang program to count digits of given number using recursion

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

Counting digits of given number using recursion in Golang

Problem Solution:

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.

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 code to count digits of given number using recursion

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

Golang Recursion Programs »






Comments and Discussions!

Load comments ↻






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