Palindrome Program in C++ using for loop

In this post, we are going to make a palindrome program in c++ using for loop and recursion.
In this post, we are going to make a palindrome program in c++ using for loop and recursion. We will make a program that will check whether the given word or sentence is a palindrome or not.

A palindrome is a word, number, phrase, or another sequence of characters that reads the same backward as forward, such as madam or racecar.

C++ program to Check for Palindrome Numbers

Palindrome Program in C++ using for loop

In this program, we run a for loop from 0 to n/2 where n is the size of the string. We are comparing character at an ith position with character at the n-i-1 position.

In short, we are comparing the first character with the last character, then the second character with the second last character and so on.

If an ith character is not the same as the character at the n-i-1 position then the input string is not a palindrome
#include<iostream>
#include<string> using namespace std; int main() { string str; cout<<"Enter String:"; getline(cin,str); int n=str.size(); int flag=0; for(int i=0;i<=n/2;i++) { if(str[i]!=str[n-i-1]) { flag=1; break; } } if(flag==0) cout<<"Yes, it is a palindrome"<<endl; else cout<<"No, it is not a palindrome"<<endl; return 0; }

Enter any number or word: madam 
Yes, it is a palindrome

Palindrome Program in C++ using reverse function

In this program, I made a string named "rev" which is the reverse of that string that is given by the user. Then, I compare them if they are the same then the input string is a palindrome.

If the reversed string is not the same as the input string then the input string is not a palindrome.

#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<<"Yes, it is a palindrome"<<endl;  
    else
        cout<<"No, it is not a palindrome"<<endl;
    return 0;                          
}

Palindrome String in Cpp using Recursion

In this program, we will check the String palindrome in C++ using recursion.
#include <bits/stdc++.h>
using namespace std;

bool palindrome(char s[],int i=0){
    
    static int n=strlen(s);
   
    if(i>n/2)
    return true;
    
    return s[i]==s[n-i-1]&& palindrome(s,i+1);
    
}
int main() {
	
	char input[50];
    cin >> input;
	if(palindrome(input))
	cout<<input<<" is a Palindrome"<<endl;
	else
	cout<<input<<" is not a Palindrome"<<endl;
	return 0;
}

Enter String: gtg
gtg is a Palindrome

About This Post:

Hey! Hope you are doing well. If you have doubts related to Palindrome Program in C++, comment below. We will invite you to google meet and clear all your doubts regarding this program, which will check given string is palindrome or not.

Post a Comment

Please do not enter any spam link in the comment box.