Scala program to check palindrome

1. Introduction

A palindrome is a word, phrase, number, or any sequence of characters which reads the same backward or forward. Examples include words like "radar" and "level", or numbers like 121. Detecting palindromes is a classic problem in programming and computer science. In this post, we'll see how to determine if a given string is a palindrome using Scala.

2. Program Steps

1. Set up the Scala environment.

2. Create an object to house the main function.

3. Accept or define a string input.

4. Implement a function to determine if the string is a palindrome.

5. Call the palindrome-checking function and print the result.

6. Run the program.

3. Code Program

object PalindromeApp {
  def main(args: Array[String]): Unit = {
    // Define a string
    val str = "radar"

    println(s"Checking if '$str' is a palindrome.")

    // Check if the string is a palindrome using the isPalindrome function
    if (isPalindrome(str)) println(s"'$str' is a palindrome!")
    else println(s"'$str' is not a palindrome.")
  }

  // Function to check if a string is palindrome
  def isPalindrome(s: String): Boolean = {
    s == s.reverse
  }
}

Output:

Checking if 'radar' is a palindrome.
'radar' is a palindrome!

Explanation:

1. We begin with an object named PalindromeApp. In Scala, the main method, the program's entry point, resides inside an object.

2. Inside the main function, we define a string, str, for which we want to check palindromicity.

3. We notify the user which string we are checking by printing it.

4. The function isPalindrome holds the logic to verify if a string is a palindrome. It takes advantage of Scala's built-in string reverse method. If the string and its reverse are identical, the string is a palindrome.

5. Inside the main function, we utilize the isPalindrome function to check the palindromicity of our string and then print the outcome.

6. As shown in the output, when the program runs, it reveals whether the provided string is a palindrome or not.


Comments