×

Palindrome Using While Loop in C++

A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM.

Like other programming languages, C++ also allows us to perform various operations. With the help of some examples, we'll explore how to verify the palindrome program in C++. Before we go into that, let's look at a palindrome. A palindrome is a result that gets the same value when the original value is reversed. Palindrome logic is as straightforward as it appears. For example, if you reverse MADAM, you'll get the same result: MADAM. That’s why, MADAM is a Palindrome value.

Here are some examples to see if they are palindromes or not:

  1. 242: It is a palindrome because the reverse is242.
  2. SOS: It's a palindrome because the reverse is SOS.
  3. 12341: This is not a palindrome because the reverse is 12341.
  4. java: It is not a palindrome because the reverse is avaj.

We can now tell whether the case, as mentioned earlier, is a palindrome or not. However, we solved the examples above orally. Let's look at how this verbal reasoning works in a computer language in C++. Before we move on the program, let's look at the algorithm to find the Palindrome.

The basic algorithm for testing Palindrome in a C++ program:

Step 1. Start

Step 2. Take input from the user.

Step 3. Save the value of the input into a temporary variable.

Step 4. Find the inverse of inserted value.

Step 5. Compare the values of both reverse and temporary variables.

Step 6. Print "it as a palindrome" if both values match.

Step 7. Print "it is not a palindrome" if both values do not match.

Step 8. Stop.

What is while Loop?

A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the condition no longer met.

The syntax of the while loop

while(condition)
                     {
                        statement(x);
                     }

Algorithm:

Step 1: Start.

Step 2: Read a number, num.

Step 3: Assign temp=num and rev=0.

Step 4: Compute r=num/10;

                               Rev= rev*10+r;

                                Num= num/10;

Step 5: If( rev== num ) print it is a palindrome.

               Else print it is not a palindrome.

Step 6: End

Flowchart:

Palindrome Using While Loop in C++

Program 1: Program to print whether the number is Palindrome or not.

#include<iostream>
using namespace std;
int main()
{
int r, rev= 0, i, temp;
int num=67876;
temp = num;           //store number to temp
i=num;
while(i>0)
         {
           r= i % 10;
          rev = rev * 10 +r;
          i = i/ 10;
       }
if(temp == rev)                                   
       {
           cout << "number is palindrome"; 
      }
else
     {
             cout << "number is not a palindrome"; 
      }
return 0;
}

The output of the program:

Number is palindrome

Explanation:

In the above program, we assigned a value 67876 to integer variable num. The integer's value is saved in yet another temporary variable, “temp”.

Then, while loop is utilized, and the modulus operator is used to get the number's last digit; 1’s position is filled with the last digit, the 10's place with the second last, and so on.

After that, the last digit is deleted by dividing the number by 10. When the  value is zero, the loop ends. The reverse number is then compared to the integer value of the temporary variable. The number is a palindrome if both values are equal. The number isn't a palindrome if both aren’t equal. But, in this case, the number is Palindrome.

Program 2: Program to check whether the number taken from the user is Palindrome or not.

#include<iostream>
using namespace std;
int main()
{
int num, r, rev= 0, i, temp;
cout << "Enter random number:"; 
      cin >> num;                        // takes value from user
      temp = num;                     //store number to temp
   i=num;
while(i>0)
         {
           r= i % 10;
          rev = rev * 10 +r;
          i = i/ 10;
       }
    if(temp == rev)                                   
          {
           cout << "Given number is a palindrome"; 
          }
     else
       {
          cout << "Given number is not a palindrome"; 
       }
  return 0;

The output of the program:

Enter a random number: 121
    The given number is a palindrome.
Enter a random number: 1234
     Given number is not a palindrome.

Explanation:

The user must first enter the integer value and save it in a variable. The integer's value is subsequently saved in yet another temporary variable.

Then, while loop is utilized, and the modulus operator is used to get the number's last digit; 1’s position is filled with the last digit, the 10's place with the second last, and so on. After that, the last digit is deleted by dividing the number by 10.

When the value becomes zero, the loop ends. The reverse number is then compared to the integer value of the temporary variable. The number is a palindrome if both values are equal. The number isn't palindrome if both aren’t equal. But, in this case, the number is Palindrome.

Program 3: Program to check whether the given array is a palindrome:

Algorithm:

Step 1: Start the program

Step 2: Set the flag to unset, i.e., int flag = 0.

Step 3: Execute the Loop through the array until it reaches the size n/2.

Step 4: In a loop, determine if arr[i]! = arr[n-i-1] then set the                               

             Flag to 1 and break.

Step 5: If the flag is set at the end of the loop, print "Not   

              Palindrome," otherwise print "Palindrome."

Step 6: End.

Program:

#include <iostream>
using namespace std;
 void palindrome(int arr[], int n)
{
    // Initialise flag to zero.
    int flag = 0;
    // Loop till array size n/2.
       Int i=0;
       While(i<=n/2&&n!=0)
     {
        // Check if first and last element are different
        // Then set flag to 1.
        if (arr[i] != arr[n - i - 1])
        {
            flag = 1;
            break;
        }
       i++;
    }
         // If flag is set then print Not Palindrome
        // else print Palindrome.
    if (flag == 1)
        cout << "Not Palindrome";
    else
        cout << "Palindrome";
}
       // Driver program.
int main()
{
    int arr[] = { 1, 2, 3, 2, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    palindrome(arr, n);
    return 0;
}

Output:

Given array is a palindrome

What is reverse()  function?

Reverse() function is a predefined function in the Standard Template Library. It reverses the order of the elements in the range [first, last]. The time complexity is 0(n).

Algorithm:

Step 1: Start.

Step 2: Read str from the user.

Step 3: Assign str= temp.

Step 4: Use the reverse(str.begin(),str.end()).

Step 5: If( temp==str)

             Print it is a palindrome

             Else

             Print it is not a palindrome.

Step 6: Stop.

Program of Palindrome using Reverse() function:

#include<bits/stdc++.h>
using namespace std;
int main()
{
   string str;
   cout<<"Enter String:";
   getline(cin,str);
   string temp=str;
   reverse(str.begin(),str.end());
   if(temp==str)
      { 
           cout<<"it is a palindrome"<<endl;  
      } 
  else
      { 
           cout<< "it is not a palindrome" <<endl;
      }       
return 0;                         
}

The output of the program

Enter String: 12321
            It is a palindrome.
 Enter String: Shyam
            It is not a palindrome.              

Explanation

In this program, a string called "rev" is the inverse of the series "str" entered by the user. Then we compared them to see if they're identical or not. And, if both are identical, then the input string/number is palindrome. If the reversed string is not the same as the input string, the input string is not palindrome.


Related Topics

gmtime() function in C/C++

C++ language is used to make high-performance applications that can work efficiently. It is one of the world's most popular languages. It is an object-oriented and high-level programming language, which...

4 minutes read.

Assertions in C/C++

Assertions are the statements used to check presumptions which is made by the programmers. Example: Assertion is used to verify whether the malloc returned by the pointer is NULL or not. For...

4 minutes read.

C++ | C Plus Plus Data type

Data type in every language is very important. Data type means the different kinds of data that are supported by a particular programming language. A computer language’s data types specify the...

15 minutes read.

Difference between C and C++

What do you mean by C? C is a machine-independent structure or procedural oriented computer language that is widely utilized in a variety of applications. C is a fundamental programming language...

4 minutes read.

Computing index using Pointers Returned by STL Functions in C++

In this tutorial we will learn how to compute index using pointers which returned by STL functions in C++. Many built-in C++ functions return pointers to memory places that provide...

2 minutes read.

4 Pillars of OOPs

OOPs OOPS means Object Oriented Programming System Structure. Object oriented Programming is defined as an approach that provides a way of modularizing programs by creating partitioned memory area for both data...

11 minutes read.

Implementing the sets without C++ STL containers

Many practical features and tools in C++ support us in programming competitions. One of these parts is a set from the Standard Template Library (STL), which offers an effective way...

6 minutes read.

Message Passing in C++

The act of sending and receiving information by an object is referred to as communication, and all communication between objects that takes place via message is known as message passing....

1 minute read.

How to create a button in C++

A button is an option through which a user can control to click a provided input to an application. There are several buttons, each with different styles, to maintain the...

3 minutes read.

C ++ Program: Alphabet Triangle and Number Triangle

Alphabet Triangle and Number Triangle An alphabet triangle is a triangle that typically looks like a pyramid or other triangles like an isosceles triangle, a right-angled triangle consisting of similar or...

4 minutes read.

Leap Year Program in C++

What is a Leap Year? A solar year is the length of time that it takes for Earth to orbit the Sun - approximately 365.25 days. In a calendar year, we...

4 minutes read.

Private Inheritance in C++

Private inheritance is an inheritance in object-oriented programming (OOP) languages where a subclass derives from a superclass. Still, the derived class does not inherit the public and protected members of...

7 minutes read.

Returning a Function Pointer from a Function in C/C++

Pointers to functions can be used in the C programming language just like standard data pointers such as "int *," "char *," etc. The following is a basic example of a...

3 minutes read.

Reserved Keywords in C++

What are reserved keywords in C++? There are a few keywords that cannot be used as identifiers as those words are reserved for some other purposes, such keywords are called reserved...

15 minutes read.

Palindrome Using While Loop in C++

A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++ also allows...

6 minutes read.

rand() and srand() in C / C++

In this tutorial, we'll explore the syntax, usage, and examples of the C++ STL functions rand() and srand(). What exactly is rand()? The C++ STL's built-in rand() function is defined in the...

3 minutes read.

Exception Handling in C++ vs Java

Nowadays, exception handling is a feature found in virtually all object-oriented languages. We can also find this type of feature in Java and C++. The try-catch and block is required...

3 minutes read.

Accumulate() and partial_sum() in C++ STL Numeric header

The C++ STL's numeric library includes the numeric header. This library provides efficient numeric arrays, support for random number generation, and fundamental mathematical operations and types. Several of the numeric...

3 minutes read.

Similarities between C++ and Java

People who are preparing for software engineering roles must have come across either one of these languages because as all the companies do not accept python for hiring a fresher...

3 minutes read.

Reverse function in C++

The function std::reverse() is included in the standard template library of C++. It takes in a beginning and ending iterator, reversing the order. To use the reverse statement, we need...

2 minutes read.