Thread: Converting Decimal to Binary Numbers using Recursion

  1. #1
    Registered User
    Join Date
    Oct 2005

    Converting Decimal to Binary Numbers using Recursion

    I am trying to make a program that will convert a decimal number to its binary equivilant. It will output the first number but I am having trouble figuring out how to use the previously found quotient to find a new quotient. I tried using loops to do this and they are always infinite.

    Here is the code I have written so far

    #include <iostream>
    using namespace std;
    void convert (int);
    int main ()
    	int num;
    	cout <<"Please enter a number to convert" <<endl;
    	convert (num);
             return 0;
    void convert (int num)
    	if (num>0)
    		double quotient,remainder;
    		if (quotient==0)
    			cout <<" ";
    		    if (remainder==0)
    			else if (remainder==1)
    		cout<< " ";

  2. #2
    Moderately Rabid Decrypt's Avatar
    Join Date
    Feb 2005
    Milwaukee, WI, USA
    If I understand what you want to do correctly, loops will be the way to go. What loops have you tried? It was most likely a problem with the way you implemented the loop that was causing a problem, as opposed to the idea of using loops messing things up.
    There is a difference between tedious and difficult.

  3. #3
    Registered User
    Join Date
    Feb 2003
    Jaisch. you're on the right track, but:
    1: you forgot the recursion; i.e. you didn't deal with the whole situation when quotient != 0
    2: You still have more to do when quotient == 0
    3: Your algorithm is going to find 2^0, then 2^1, then 2^2, etc., which is fine but you're going to end up printing the binary number in reverse unless you do something to handle that.
    4: Why output anything when num == 0? Just return.
    Last edited by R.Stiltskin; 10-24-2005 at 10:38 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Binary to Base 10 decimal conversion
    By JFonseka in forum C Programming
    Replies: 13
    Last Post: 11-20-2007, 04:14 PM
  2. Converting decimal to binary
    By ubernos in forum C Programming
    Replies: 3
    Last Post: 12-06-2005, 10:09 AM
  3. Confused by expression.
    By Hulag in forum C Programming
    Replies: 3
    Last Post: 04-07-2005, 07:52 AM
  4. binary to decimal
    By miryellis in forum C Programming
    Replies: 7
    Last Post: 03-14-2004, 08:35 PM
  5. binary to decimal
    By jk81 in forum C Programming
    Replies: 1
    Last Post: 09-13-2002, 05:20 AM