Go Program to Check if a Given Number is a Palindrome
This program checks whether a given number is a palindrome. A palindrome is a number that reads the same backward as forward, such as 121 or 1331.
Program Structure and Explanation
The program is written in the Go programming language and consists of the following parts:
- Package Declaration: Declares the main package which is required for an executable program.
- Imports: Imports the fmt package for formatted I/O operations.
- isPalindrome Function: A function that checks if a given integer is a palindrome.
- Main Function: The entry point of the program where user input is taken and the isPalindrome function is called.
Go Code:
// Package declaration
package main
// Importing necessary package
import (
"fmt"
)
// isPalindrome function checks if a given number is a palindrome
func isPalindrome(number int) bool {
// A negative number cannot be a palindrome
if number < 0 {
return false
}
// Initialize variables to store the original number and its reverse
original := number
reversed := 0
// Loop to create the reverse of the number
for number != 0 {
// Get the last digit of the number
digit := number % 10
// Append the digit to the reversed number
reversed = reversed*10 + digit
// Remove the last digit from the number
number /= 10
}
// Check if the original number and reversed number are the same
return original == reversed
}
// Main function
func main() {
// Variable to hold user input
var number int
// Prompt the user for input
fmt.Print("Enter a number: ")
fmt.Scan(&number)
// Check if the number is a palindrome and print the result
if isPalindrome(number) {
fmt.Printf("%d is a palindrome.\n", number)
} else {
fmt.Printf("%d is not a palindrome.\n", number)
}
}
Explanation:
isPalindrome Function:
- First, it checks if the number is negative. If it is, the function returns false because a negative number cannot be a palindrome.
- It then initializes two variables:
original
to store the original number andreversed
to build the reversed number. - A loop runs while the number is not zero, extracting the last digit of the number and appending it to
reversed
. The last digit is then removed from the number. - Finally, the function checks if the original number is equal to the reversed number and returns the result.
Main Function:
- It declares a variable
number
to hold the user input. - Prompts the user to enter a number and reads the input using
fmt.Scan
. - Calls the
isPalindrome
function with the user input and prints whether the number is a palindrome or not.