This program checks whether a given number is a palindrome or not.
#include <iostream>
using namespace std;
int main(){
int x, temp, r, rev = 0;
cout << "Enter number to check palindrome or not" << endl;
cin >> x;
temp = x;
while (x != 0) {
r = x % 10;
rev = rev * 10 + r;
x = x / 10;
}
if (temp == rev) {
cout << temp << " is palindrome number" << endl;
} else {
cout << temp << " is not palindrome number" << endl;
}
return 0;
}
Enter number to check palindrome or not: 262
262 is palindrome number
Enter number to check palindrome or not: 13
13 is not palindrome number
x
variable.temp
variable to store the original value of x
because x
will be modified later in the program.while
loop to reverse the digits of the x
variable and store the result in the rev
variable.a. The loop continues until x
becomes 0.b. In each iteration, the program extracts the last digit of x
using the modulus operator (%
) and stores it in the r
variable.c. The program then updates the rev
variable by adding the r
multiplied by 10 to its current value.d. Finally, the program divides x
by 10 to remove the last digit.temp
is equal to rev
.a. If they are equal, the program prints that the input number is a palindrome.b. If they are not equal, the program prints that the input number is not a palindrome.This C++ program checks if a given string or number is a palindrome or not. A palindrome is a string or number that reads the same backward as forward.
The program takes an input string from the user and stores it in the variable str
. Then, it calculates the length of the string and stores it in the length
variable.
Next, it uses a for loop to iterate through the string from the end to the start, and concatenates each character to the reverse
variable.
Finally, it checks if the str
is equal to the reverse
, and if they are equal, it prints the message “str
is a palindrome”. Otherwise, it prints the message “str
isn’t a palindrome”.
#include <iostream>
using namespace std;
int main(){
string str, reverse = "";
cout << "Enter a string or number to check palindrome number: ";
cin >> str;
int length = str.length();
for (int i = length - 1; i >= 0; i--) {
reverse = reverse + str.at(i);
}
if (str == reverse) {
cout << str << " is a palindrome." << endl;
} else {
cout << str << "isn't a palindrome." << endl;
}
return 0;
}
wow is a palindrome.