Loop Case Study in C++: Checking Palindromes

This section presents a program that tests whether a string is a palindrome.

A string is a palindrome if it reads the same forward and backward. The words “mom,” “dad,” and “noon, ” for example, are palindromes.

How do you write a program to check whether a string is a palindrome? One solution is to check whether the first character in the string is the same as the last character. If so, check whether the second character is the same as the second-last character. This process continues until a mismatch is found or all the characters in the string are checked, except for the middle character if the string has an odd number of characters.

To implement this idea, use two variables, say low and high, to denote the position of two characters at the beginning and the end in a string s, as shown in Listing 5.16 (lines 13, 16). Initially, low is 0 and high is s.length() – 1. If the two characters at these positions match, increment low by 1 and decrement high by 1 (lines 27-28). This process continues until (low >= high) or a mismatch is found.

Listing 5.16 TestPalindrome.cpp

1 #include <iostream>

2 #include <string>

3 using namespace std;

4

5 int main()

6 {

7    // Prompt the user to enter a string

8    cout << “Enter a string: “;

9    string s;

10   getline(cin, s);

11

12    // The index of the first character in the string

13    int low = 0;

14

15    // The index of the last character in the string

16    int high = s.length() – 1;

17

18    bool isPalindrome = true;

19    while (low < high)

20    {

21       if (s[low] != s[high])

22       {

23           isPalindrome = false; // Not a palindrome

24           break;

25       }

26

27       low++;

28       high–;

29    }

30

31    if (isPalindrome)

32       cout << s << ” is a palindrome” << endl;

33    else

34       cout << s << ” is not a palindrome” << endl;

35

36    return 0;

37 }

The program declares a string (line 9), reads a string from the console (line 10), and checks whether the string is a palindrome (lines 13-29).

The bool variable isPalindrome is initially set to true (line 18). When comparing two corresponding characters from both ends of the string, isPalindrome is set to false if the two characters differ (line 23). In this case, the break statement is used to exit the while loop (line 24).

If the loop terminates when low >= high, isPalindrome is true, which indicates that the string is a palindrome.

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *