×

Palindrome using For 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 For Loop?

A for loop is a repetitive control structure that allows you to create a loop to execute a specific number of times efficiently.

The syntax of for loop

In C++, a for loop is written as

for (initialize; condition; increment) 
 {
 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 For loop in C++

Program 1:

#include<iostream>
 using namespace std;
 int main()
 {
 int r, rev= 0, i, temp;
int num=12321;
 temp = num; //store number to temp
 for(i = num; i >0;i = i/ 10)
         {
               r= i % 10;
               rev = rev * 10 +r;
         }
 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 12321 to integer variable num. The integer's value is saved in yet another temporary variable, “temp”.

Then, the For 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 this, the last digit is 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 the user
 temp = num; //store number to temp
     for(i = num; i >0; i = i/ 10)
          {
            r= i % 10;
              rev = rev * 10 +r;
            
         }
    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: 545
The given number is a palindrome.
Enter a lucky number: 9878
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, For 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 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

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.

Code:

#include <iostream>
using namespace std;
 void palindrome(int arr[], int n)
{
    int flag = 0;
for(i = 0;  i<=n/2&&n!=0;i++)
          {
         if (arr[i] != arr[n - i - 1])
             {
                   flag = 1;
                   break;
            }
         }     
         // 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

Object in C++

In this article, we will learn about Object in C++. In short, an object is a stateful entity with behaviour. Data is referred to as state, and functionality is referred to...

3 minutes read.

Implementation of a Falling Matrix in C++

In many Hollywood and Bollywood movies, we might have seen a programmer who will be referred to as a hacker all the time for some random reason which the writer...

3 minutes read.

How to make a password program in C++

Before understanding the password program, one must know about a password and why it is required. Password: A password is a word that permits access to somewhere or something. A password...

4 minutes read.

Include Guards in C++

In C++ programming, we frequently utilize a class more than once, so it is necessary to create a header file and include it in the main program. Now, occasionally a...

3 minutes read.

C++ Pipe Tutorial

A pipe is a mechanism for inter-process communication (IPC) in a Unix-like operating system. It allows two or more processes to communicate with each other by sending and receiving data...

3 minutes read.

Quick Sort in C++

Quick sort is an efficient, in-place, comparison-based sorting algorithm that uses a divide-and-conquer strategy to sort an array or list of elements. First a pivot element is selected from the...

4 minutes read.

C++ Program to Print Fibonacci Triangle

Fibonacci Triangle Program in CPP Definition: Fibonacci Triangle as the name suggests is the same as the Fibonacci number series where the next element is the sum of the previous two elements....

3 minutes read.

Ascending order in C++

In C++, the term "ascending order" refers to a specific order in which a list of elements is arranged. When a list of elements is arranged in ascending order, the...

3 minutes read.

C++ if-else

C++ if else Control Statement if else control statement in C++ is used to control the program flow in a two-way direction. When condition returns a true value, then the program executes if condition block otherwise...

1 minute read.

Tensorflow in C++

With cppflow, you can execute TensorFlow models in C++ without Bazel, TensorFlow installation, or TensorFlow compilation. Tensor manipulation, eager execution, and running stored models straight from C++ are all possible. Knowing...

7 minutes read.

C++ Forward Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

Passing a Vector to a function in C++

A pointer is sent to the function when we feed it an array. However, there are two ways to pass a vector: Pass by Value Pass by Reference A copy of a vector...

3 minutes read.

C++ Maximum Index Problem

Given an array A[] of positive integers. We will find the maximum of (j-i) such that i and j are the indexes of A[] and A[i] <= A[j], i<=j For...

5 minutes read.

Type difference of Character literals in C VS C++

Character literals in C: In C, a character literal is represented by a single character enclosed in single quotes, such as 'a' or 'b'. It is of type int. This means...

5 minutes read.

swap() function in C++

Swap() function: swap() function in C++: swap() function is a pre-define function in c++ present in STL( Standard template library ). It is used to swap two numbers. It takes two mandatory...

6 minutes read.

Data Hiding in C++

C++ : High-performance apps can be made using the cross-platform language C++. Bjarne Stroustrup created C++ as an addition to the C language. Programmers have extensive control over memory and system...

3 minutes read.

C++ add two numbers using the function

Here we will learn how to add two numbers by creating function in C++. Let’s learn this with help of example. Code: - #include <iostream> using namespace std; int add_two_no(int a, int b); int main(){   int...

1 minute read.

Scope Resolution Operator in C++

The scope resolution operator and its different usage in the C++ programming language will be discussed in this section. The scope resolution operator is used to refer to an out-of-scope...

6 minutes read.

Continue in C++ While loop

Continue statement: Inside the loop, the continue statement is used to control the loop. C++ utilizes the continue keyword to implement the continue statement, which transfers the program's flow at the...

4 minutes read.

Decltype type Specifier in C++

The primary use of C++ decltype is to inspect the declaration type of an entity in an expression. The auto keyword can declare a particular type of variable, whereas the...

4 minutes read.