Go Program to find First Digit of a Number

Write a Go Program to find the First Digit of a Number using For loop. The for loop condition (for firstDigit >= 10) returns true until the number is greater than or equals to 10. We divide the number by 10 (firstDigit = firstDigit / 10), which will return the first value after all the iterations.

package main

import "fmt"

func main() {

    var firstDigit, number int

    fmt.Print("Enter any Number to return First Digit = ")
    fmt.Scanln(&number)

    firstDigit = number
    for firstDigit >= 10 {
        firstDigit = firstDigit / 10
    }

    fmt.Println("The First Digit of this Number    = ", firstDigit)
}
SureshMac:Goexamples suresh$ go run firstDigit1.go
Enter any Number to return First Digit = 3478
The First Digit of this Number    =  3
SureshMac:Goexamples suresh$ go run firstDigit1.go
Enter any Number to return First Digit = 9876
The First Digit of this Number    =  9

Go Program to find First Digit of a Number using Functions

In this Golang program, we created a (func findfirstDigit(number int)) function that returns the first digit of a given number. Next, we call this function from main.

package main

import "fmt"

func findfirstDigit(number int) int {
    for number >= 10 {
        number = number / 10
    }
    return number
}
func main() {

    var firstDigit, number int

    fmt.Print("Enter any Number to return First Digit = ")
    fmt.Scanln(&number)

    firstDigit = findfirstDigit(number)

    fmt.Println("The First Digit of this Number    = ", firstDigit)
}
Go Program to find First Digit of a Number 2