GO Program to check palindrome number

For a better understanding of this example, we always recommend you to learn the basic topics of Golang programming listed below:

What is a palindrome number?

A number is said to be palindrome number when it remains the same when its digits are reversed.

Example: 12321, 75257

How to check palindrome number

To check the given number for palindrome, hold the given number into a temporary variable.Reverse the given number and then compare the reversed number with the temporary variable. If both of them are same then print "palindrome number" else print "not palindrome".

How to check palindrome numbers in the Go Program

Here we are using a variable num to hold the number to check. Another temporary variable temp is used to check it when the original has been reversed. Using a for loop last digit of the number is separated. For this we are dividing the given number by 10. Here we are using the arithmetic operator modulus% to perform the operation. This value is stored into another variable rem. rem = temp % 10. Add this result to the variable rev where the reversed form of the given number is to be stored. Before adding  to rev we need to multiply the current data in the rev with 10 and add rem with it. rem = temp % 10 , rev = rev*10 + rem. This is  performed in a for loop.

syntax for for loop

 


for    initializer; condition;   incrementor {
}


If else statement is used to check whether the given number is equal to the reversed number. if the value of num=rev then print a message "palinndrome number" using the function fmt.println(). else print "not palindrome"

 

syntax for if...else

 


if condition {
//do some instructions
}else {
//do some instructions

ALGORITHM

STEP 1: Import the package fmt

STEP 2: Start function main()

STEP 3: Declare the variable Num, rem, rev, temp

STEP 4: Read the number Num using fmt.Scanfln()

STEP 5:Initialise integer rev=0

STEP 6: Reverse the given number using for loop as (for temp := Num; temp > 0; temp = temp / 10)

STEP 7: Finding rem = temp % 10 and rev = rev*10 + rem in the loop

STEP8: Use If else statement (if Num == rev) to check whether the reverse number equals a given number

STEP9: If true, it is a palindrome, otherwise not a palindrome number.

 

GO Source Code

                                          package main
import "fmt"

func main() {
    var Num, rem int
    fmt.Print("Enter the number to check Palindrome = ")
    fmt.Scanln(&Num;)
    rev := 0
    for temp := Num; temp > 0; temp = temp / 10 {
        rem = temp % 10
        rev = rev*10 + rem
    }

    fmt.Println("The Reverse of the number = ", rev)
    if Num == rev {
        fmt.Println(Num, " is a Palindrome number")
    } else {
        fmt.Println(Num, " is Not a Palindrome number")
    }
}
                                      

OUTPUT

Enter the number to check Palindrome = 191
The Reverse of the number =  191
191  is a Palindrome number