palindrome no example
Here is an example of C++ code to check if a number is a palindrome, along with explanations for each step:
#include <iostream>
using namespace std;
int main() {
int num, reversedNum = 0, remainder, originalNum;
cout << "Enter an integer: ";
cin >> num;
originalNum = num;
// Reversing the number
while (num != 0) {
remainder = num % 10;
reversedNum = reversedNum * 10 + remainder;
num /= 10;
}
// Checking if the number is a palindrome
if (originalNum == reversedNum)
cout << originalNum << " is a palindrome.";
else
cout << originalNum << " is not a palindrome.";
return 0;
}
Explanation:
The code starts by including the necessary header file
iostream
and using thestd
namespace to avoid typingstd::
before standard library functions.The
main()
function is defined, which is the entry point of the program.Variables
num
,reversedNum
,remainder
, andoriginalNum
are declared.num
will hold the user input,reversedNum
will store the reversed number,remainder
will store the remainder of the division, andoriginalNum
will store the original input number.The user is prompted to enter an integer using the
cout
stream and the input is stored in the variablenum
using thecin
stream.The value of
num
is assigned tooriginalNum
to keep a copy of the original input.The code enters a
while
loop that continues untilnum
becomes zero. This loop reverses the number by repeatedly dividingnum
by 10 and adding the remainder toreversedNum
after multiplying it by 10.After the loop ends, the code checks if the
originalNum
is equal toreversedNum
. If they are equal, the number is a palindrome, and a message is printed to the console confirming this. Otherwise, a message is printed indicating that the number is not a palindrome.The
main()
function returns 0, indicating successful execution of the program.
This code takes an integer input from the user and checks if it is a palindrome number. A palindrome number is a number that remains the same when its digits are reversed.