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

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 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 {
		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)


Enter number: 3624
Count of digits is: 4


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{
    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

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.