what's wrong with this if function

This is a discussion on what's wrong with this if function within the C Programming forums, part of the General Programming Boards category; Well, this seems to be a bit strange.. this is the simple palindrome code.. Code: # include <stdio.h> int palindrome ...

  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
    21,728
    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.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    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, 10: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


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21