Thread: what's wrong with this if function

  1. #1
    Registered User
    Join Date
    Jan 2011
    Posts
    113

    what's wrong with this if function

    Well, this seems to be a bit strange..
    this is the simple palindrome code..

    Code:
    # include <stdio.h>
    
    int palindrome (int n)
    {  
       int rev=0, k;
       
       while (n!=0)
       {
          k = n%10;
          rev = rev * 10 + k;
          n = n/10;     
       }
       
       if (rev == n)
         return n;
       else
         return 0;
    }
    
    int main (void)
    {
       int n=9009;
       
       printf("%d",palindrome(n));
    }
    As we know the input N is palindrome.. but its returning 0..
    I checked the value of rev after the calculation ... it went fine.
    but when I use this condition
    if (rev ==n)
    something is going wrong inside..
    I checked the value of rev & n values after that .. they get turning to 0;

    why ?

    where's the little bug, that's hiding?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Notice that at the end of the loop, n == 0. Therefore, for rev == n to evaluate to true, rev must be 0, in which case 0 is returned. Therefore, the function always returns 0.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Jan 2011
    Posts
    113
    oops .. got the bug.. its very silly.
    n is tending to 0 in the whole iteration .

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. wrong wrong with my xor function?
    By Anddos in forum C++ Programming
    Replies: 5
    Last Post: 04-26-2009, 01:38 PM
  2. what is wrong with my function?
    By liaa in forum C++ Programming
    Replies: 7
    Last Post: 03-21-2009, 09:04 AM
  3. What is wrong with this function?
    By shardin in forum C Programming
    Replies: 20
    Last Post: 09-24-2007, 01:50 PM
  4. What is wrong with my function?
    By s0beit in forum C++ Programming
    Replies: 6
    Last Post: 12-14-2006, 11:57 PM
  5. Can anyone see what's wrong with this function?
    By Clyde in forum C++ Programming
    Replies: 2
    Last Post: 05-18-2002, 03:26 PM

Tags for this Thread