GO Program to count digits in a number

How to count digits in a number

Here we are explaining how to count digits in a number in the Go program. We can use the built-in function fmt.println() to print anything and fmt.scanln() for reading the values. This function is defined under the fmt package and it helps to write standard output. In order to use these functions, we need to import the “fmt” package.

 

How to count digits in a number in the GO Program

We are using fmt.println() function for printing the string to the output screen. Here we are showing how to count digits in a number in the Go language. Here variables holding the number whose digits have to be count, and variable C for holding the count. The digits are calculated as N=N/10 in a for-loop. Given below are the steps which are used in the Go program. 

ALGORITHM

STEP 1: Import the package fmt

STEP 2: Start function main()

STEP 3: Declare the variable N, C 

STEP 4: Initialise integer variable C=0

STEP 5: Read the number N using fmt.Scanln()

STEP 6: Use for loop for count the digits as N=N/10 and C=C+1

STEP 7: Print the count using fmt.Println()

 

GO Source Code

                                          package main
import "fmt"

func main() {
    var N, C int
    C = 0
    fmt.Print("Enter any number for digits count = ")
    fmt.Scanln(&N)

    for N > 0 {
        N = N / 10
        C = C + 1
    }
    fmt.Println("The number of digits = ", C)
}
                                      

OUTPUT

Enter any number for digits count = 4586

The number of digits = 4