In: Computer Science
A palindromic number is a number that remains the same when its digits are reversed. For examples, 1, 11, 99, 121 are palindromic. Write a program that takes one array of 10 positive integers as input and output all the palindromic numbers in this array. We assume that each input number is valid, i.e., a positive integer.
Hint: You can consider the following steps to check whether a number (e.g., 121) is palindromic • Store this number to one variable, e.g., temp = 121. • Calculate the value of the number when all the digits in temp are reversed, e.g., extracting each digit in temp from the right-hand side to left-hand side, and calculating the value at the same time. • Check whether the original value equals to this calculated value.
write it in c++
Answer
here we can use 10 elements of integer array for perform the task, Here we take each value in the array and stored into a temporary variable then we can reverse that integer in best method. finally reversed integer matched with corresponding array value, if it is true then it is a palidrom. so here is the code for above problem.
// C++ code for finding palidromes in a given array of elements;
#include<bits/stdc++.h>
using namespace std;
int main()
{
//sample input array. which contain 10 elements.
int arr[] = {121,56,434,1,2,121,10,12,131,178};
//set n as total number of elements.
int n = 10;
//temp is used to store temporary value of each item in array
int temp;
// d hold the reminder at the time of loop.
int d;
// rev holds the reversed value of integer.
int rev;
for (int i = 0; i <n; i++)
{
temp=arr[i];
rev = 0;
//very important part in this, reverse an integer.
while (temp > 0)
{
d = temp % 10;
rev = rev * 10 + d;
temp = temp / 10;
}
// checking the reversed integer is same as the array value. then it is palidrome.
if(arr[i]==rev)
{
cout<<rev<<"\n";
}
}
return 0;
}
output
You can change the values of the array as you need. So here the porgram pop out the palidromes only. Any doubt please comment
Thanks in advance