0

Why does the first one work and the second doesn't?

#include <iostream> using namespace std; int main() { int n,num,rev=0,digit; cin>>num; n=num; do { digit=num%10; rev=(rev*10)+digit; num/=10; }while(num!=0); if (n==rev){ cout<<n<<" is a palindrome"; } else{ cout<<n<<" is not a palindrome"; } return 0; } This one work just fine #include <iostream> using namespace std; int main() { int num,rev=0,digit; cin>>num; while(num!=0){ digit=num%10; rev=(rev*10)+digit; num/=10; } if (num==rev){ cout<<num<<" is a palindrome"; } else{ cout<<num<<" is not a palindrome"; } return 0; } This one keeps giving me 0 as a value, and I have no Idea why.

30th Sep 2021, 2:28 PM
Rakin
Rakin - avatar
5 ответов
+ 1
In first snippet, you copied <num> into <n> before running the loop. You compare <n> to <rev> afterwards. This is fine as <n> contains the original value of <num>. In second snippet, you went on with the loop, which stops when <num> becomes zero. You didn't have a copy of the original input.
30th Sep 2021, 2:45 PM
Ipang
+ 1
Rakin in the second one you're printing the value of num and not n, n does not exist, store a copy of the original input
30th Sep 2021, 2:43 PM
Eashan Morajkar
Eashan Morajkar - avatar
+ 1
#include <iostream> using namespace std; int main() { int num,n,rev=0,digit; cin>>num; n=num; while(num!=0){ digit=num%10; rev=(rev*10)+digit; num/=10; } if (n==rev){ cout<<n<<" is a palindrome"; } else{ cout<<n<<" is not a palindrome"; } return 0; }
30th Sep 2021, 2:56 PM
Eashan Morajkar
Eashan Morajkar - avatar
+ 1
Oh Ok I got it now. Thanks to everyone who replied. I see what I did wrong
30th Sep 2021, 3:03 PM
Rakin
Rakin - avatar
0
the num variable is 0
30th Sep 2021, 2:45 PM
Eashan Morajkar
Eashan Morajkar - avatar