×

Palindrome using Do-while loop in C++

What is Palindrome?

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:

1. Start

2. Take input from the user.

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

4. Find the inverse of inserted value.

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

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

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

8. Stop.

What is Do-While Loop?

An iterative loop that checks the condition at the end.
The Do-While loop can be used whenever a test condition is specific, as the control enters the loop at a minimum once before the condition is evaluated. This loop checks the given condition after the execution of looping statements.

The loop actions or statements will be repeated infinitely as long as the test requirements are met.

Note: DO-WHILE LOOP means “first do it, then check”.

Syntax:

The Syntax of the DO-WHILE loop is:

Do
           { 
            statement(s);
           } 
         while(expression);

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 of finding the Palindrome:

Palindrome using Do-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=4554;
temp = num;           //store number to temp
i=num;  
 do{
           r= i % 10;
          rev = rev * 10 +r;
          i = i/ 10;
       }while(i>0);
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 4554 to integer variable num. The integer's value is saved in another temporary variable, “temp”.

Then, Do-while loop is utilized, and the modulus operator is used to get the number's last digit. Here, 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;  
i=num;                   //store number to temp
            do {
           r= i % 10;
             rev = rev * 10 +r;
           i = i/ 10;
        }while(i>0);
   if(temp == rev)                                   
          {
           cout << "The given number is a palindrome"; 
          }
     else
       {
          cout << "The 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 saved in another temporary variable.

Then, Do-while loop is utilized, and the modulus operator is used to get the number's last digit. Here, 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 a palindrome if both aren’t equal. But, in this case, the number is Palindrome.

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

#include <iostream>
using namespace std;
 void palindrome(int arr[], int n)
{
    int flag = 0;
    Int i=0;
       do
          {
         if (arr[i] != arr[n - i - 1])
             {
                   flag = 1;
                   break;
            }
           i++;
         }     
      While(i<=n/2&&n!=0)


         // If flag is set then print Not Palindrome
        // else print Palindrome.
    if (flag == 1)
        cout << "Not Palindrome";
    else
        cout << "given array is 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

C++ Bitset

Overview In C++, bitset represents a fixed-sequence of some bits values by either 0 and 1. Zero represents the value as false or unset, while 1 represents the value as true...

4 minutes read.

Preventing Object Copy in C++

C++ is an object-oriented programming language that provides the ability to create objects, define class and pass objects to functions. When passing an object to a function or returning an...

7 minutes read.

Const Keyword in C++

The const programming language keyword will be covered in this section. The constant value that cannot change during program execution is defined using the const keywords. It implies that once...

9 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.

Char Array to String in C++

Regardless of the programming language you use, data structure is critical to the success of your project. Although each programming language has its own collection of data structures, C++ contains a...

4 minutes read.

C++ Expressions

C ++ equations are made up of operators, constants and variables arranged according to language rules. It may also include function calls that give results. To calculate the value, the...

4 minutes read.

Stack in C++

Stack: The stack is a very popular data structure. It is the form of data structure that follows a particular order called FIFO(First-In-First-Out). In simple words, a stack is an Abstract...

4 minutes read.

strcat() vs strncat() in C++

In this tutorial, we will explore about strcat() and strncat() in the most usable language C++. We will also look at the difference between them. strcat() C++ is a computer language with...

4 minutes read.

Object Slicing in C++

In this article, we will learn about Object slicing. When an object from a derived class is assigned to an object from a base class in C++, these extra attributes...

3 minutes read.

How to concatenate two strings in C++

In the C++ programming language, the concatenation of two or even more strings is covered in this section. The term "string concatenation" refers to a collection of characters that join two...

4 minutes read.

Skyline Problem in C++

We have given n rectangular buildings in a 2-dimensional city. Here, to compute the Skyline of the given n rectangle structures in a two-dimensional metropolis while removing hidden lines, the...

3 minutes read.

How to create a library in C++

Before going on to the creation of a library, let’s understand its meaning. What is a library? In simple words, a library is a collection of numerous functions, methods, classes, header files...

7 minutes read.

Divide by Zero Exception in C++

We use exception handling method to handle the divide by zero exception. Dividing a number with zero is generally mathematical error. We have to exception handling method to overcome this...

2 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.

Learn C++ Tutorial

C++ Introduction C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at AT&T Bell Laboratories. It is superset (extension) of C programming language. Depending upon features supported by programming...

10 minutes read.

Palindrome using Do-while loop in C++

What is Palindrome? 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++...

5 minutes read.

Delete Operator in C++

Overview We can reserve allocation for a variable or an array at runtime in C++. Dynamic memory allocation is the term for this. After utilising a variable in C++, we must...

4 minutes read.

wcscpy(), wcslen(), wcscmp() Functions in C++

There are many built-in functions in C++ programming language which differentiate it from C programming language in most hardware-coded languages. We will now closely look into the applications of three...

4 minutes read.

C++ Program to Implement Merge Sort

C++ Program to Implement Merge Sort The technique of merge sort is based on the strategy of divide and conquer. We divide the set of while data into smaller bits, arranged...

3 minutes read.

Remove duplicates from sorted array in C++

Remove duplicates from the sorted array in C++. This same process, due to a sorted array, is to erase the redundant components from the array. Examples: Input  : arr[] = {2, 2, 2,...

4 minutes read.