I am trying to find all the palindrome numbers under a given limit number using a check function.
This is my code:
#include<iostream>
using namespace std;
int checkPalindrom(int);
int main(){
int num,sum;
int lim;
cout << "Insert limit number: ";
cin >> lim;
cout << "Palindrome numbers within the limit are: ";
for(num>0;num<=lim;num++){
sum=checkPalindrom(num);
if(num==sum)
cout << num << " ";
}
return 0;
}
int checkPalindrom(int num){
int sum=0,r;
if (num){
r=num%10;
sum=sum*10+r;
checkPalindrom(num/10);
}
return sum;
}
The result here is palindrome numbers till 9, despite 2 digits < number
Thank you in advance for your answers!
Change this
for(num>0;num<=lim;num++)
to this
for(num=0;num<=lim;num++)
in order to initialize num
.
then actually you need to make more changes. This should work:
#include<iostream>
using namespace std;
bool checkPalindrom(int);
int main() {
int num;
int lim;
cout << "Insert limit number: ";
cin >> lim;
cout << "Palindrome numbers within the limit are: ";
for (num = 0; num <= lim; num++) {
if (checkPalindrom(num))
cout << num << " ";
}
return 0;
}
bool checkPalindrom(int num) {
int n = num;
int dig, rev = 0;
while (num > 0) {
dig = num % 10;
rev = rev * 10 + dig;
num /= 10;
}
return (n == rev);
}
The solution is based in this answer.
The main problem with your code, was that you were not even using a loop, but an if statement inside your function.