Monday, December 17, 2018

Golang Example - Program to count number of digits in an integer

This example covers two programs to count the number of digits in an integer, the first program is using the iterative function, the Second program is using the Recursive function.
To understand this example, You should have following features in Go language
Both programs read an integer value from a user keyboard, find the number of digits. For example, if the user entered the number as 245, Result of these programs is 3.

Example program - count number of digits in an integer using an iterative function

The program takes an input integer from a user console, stores it in variable number, For Loop is used to iterate the digits until the condition (number != 0 ) is false ie number=0

For Input number=456, Iteration function executes the sequence of steps
  • Once First Iteration of for loop is completed, the number will be 45 and count is incremented by 1, count=1
  • After the second iteration is completed, the number will be 4 and count is incremented by 1 ie count=2
  • After the third iteration is completed, a number will be 0 and count is incremented by 1 ie count=3
  • For loop condition expression is evaluated to false(number=0), For loop is terminated
  •  the count is returned to the main function
Finally, a count is printed to console using the Println function in the main function.
package main

import "fmt"

func iterativeDigitsCount(number int) int {
 count := 0
 for number != 0 {
  number /= 10
  count += 1
 }
 return count

}
func main() {
 number := 0
 fmt.Print("Please enter number: ")
 fmt.Scanln(&number)
 fmt.Printf("Digits count of %d is %d", number, iterativeDigitsCount(number))

}
When you run the above program, Output is
Please enter number: 456
Digits count of 456 is 3
Please enter number: 2
Digits count of 2 is 1

Example program - count number of digits of an integer using the Recursive function

A recursive function is a function which calls inside the same function
Here is a recursive Function execution flow for input number=2546
recursionCountDigits(2546)
-- 1+ recursionCountDigits(254)
    -- 2+ recursionCountDigits(25)
        -- 3+ recursionCountDigits(2)
            -- 3+ 1 returns 4 to main function

Following is an example for a Recursive function to count the number of digits of a number

package main

import "fmt"


func main() {
 number := 0
 fmt.Print("Please enter number: ")
 fmt.Scanln(&number)
 fmt.Printf("Digits count of %d is %d", number, recursionCountDigits(number))

}

func recursionCountDigits(number int) int {
 if number < 10 {
  return 1
 } else {
  return 1 + recursionCountDigits(number/10)
 }
}
Output is
Please enter number: 2546
Digits count of 2546 is 4

Please enter number: 456789
Digits count of 456789 is 6

Related article


EmoticonEmoticon