Positive Binary output function

This is a discussion on Positive Binary output function within the C Programming forums, part of the General Programming Boards category; I have written a function that takes in a positive decimal and returns its Binary equivalent; however, the output always ...

  1. #1
    Registered User Unee0x's Avatar
    Join Date
    Nov 2011
    Posts
    12

    Positive Binary output function

    I have written a function that takes in a positive decimal and returns its Binary equivalent; however, the output always adds an additional zero to the binary.
    what could I do to get rid of it?
    If the number is 7, it outputs 0111 instead of 111.
    Here is my code:
    Code:
    #include <stdio.h>
    void Dec(int n)
    {
      if(n > 0)
      Dec(n/2);
      printf("%i", n%2);
    }
    int main()
    {
      int x;
      printf("Enter a Positive Decimal Number Please\n");
      scanf("%d",&x);
      Dec(x);
      printf("\n");
    }
    Thank you in advance...

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    23,617
    It looks like your if statement needs to control the printf too.
    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 Unee0x's Avatar
    Join Date
    Nov 2011
    Posts
    12
    Thank you,
    It worked perfectly once I added two curly braces around the if statement.
    Code:
    0001 #include <stdio.h>
    0002 void Dec(int n)
    0003 {
    0004   if(n > 0)
    0005 {
    0006   Dec(n/2);
    0007   printf("%i", n%2);
    0008 }
    0009 }
    0010 int main()
    0011 {
    0012   int x;
    0013   printf("Enter a Positive Decimal Number Please\n");
    0014   scanf("%d",&x);
    0015   Dec(x);
    0016   printf("\n");
    0017 return 0;
    0018 }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Binary Output
    By r_james14 in forum C Programming
    Replies: 13
    Last Post: 11-22-2011, 08:13 AM
  2. binary based output
    By mk555 in forum C Programming
    Replies: 15
    Last Post: 09-24-2004, 06:27 PM
  3. Binary Output
    By Ajsan in forum C++ Programming
    Replies: 9
    Last Post: 04-23-2004, 04:43 PM
  4. displaying binary output
    By clancyPC in forum C Programming
    Replies: 1
    Last Post: 10-14-2003, 07:32 AM
  5. Specifying binary output?
    By Hardboy in forum C++ Programming
    Replies: 3
    Last Post: 04-10-2003, 03:41 PM

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