|
-
October 6th, 2002, 02:15 PM
#1
[RESOLVED] Loop until condition met
Hi I'm trying to make a program that will convert a decimal number to binary. The problem I'm running into is making the loop that will continue out the math until it no longer needs to be carried out. The way im reaching the binary number from decimal is doing something like this:
if the number is say, 10, it would be
10 / 2 = 5 and 10 % 2 = 0
5 / 2 = 2 and 5 % 2 = 1
2 / 2 = 1 and 2 % 2 = 0 so 10 = 1010
I need the program to realize when the original number is now less than 2, so it knows to stop. The only thing I need to know is how to make the loop (I know what to put in the loop) and how to make the loop stop when the original number is less than 2. I tried using a do while but couldn't quite get the hang of it.
Help is always apprecitiated, thanks.
-
October 6th, 2002, 06:03 PM
#2
Well, I'm only a beginner myself. So, I tried your problem.
I had a couple of similar problems with it. You need to print out the answer in reverse order from which it's derived. So, what size should you set up an array if you plan to store the answers in reverse order?
So, instead of using an array and doing a lot of conversions, I simply made a recursion function. It spits out the answers in the correct order by using the stack.
Code:
#include <iostream>
using namespace std;
void DecToBin( int n );
int main()
{
int n;
cout << "Enter a number to convert: ";
cin >> n;
cout << endl;
DecToBin( n );
cout << endl;
return 0;
}
void DecToBin( int n )
{
if( n / 2)
DecToBin( n / 2 );
if( n % 2 )
cout << "1";
else cout << "0";
}
-
October 6th, 2002, 06:18 PM
#3
How about...
PHP Code:
cout << "Enter decimal number: ";
int num;
cin >> num;
short answer[20];//answer will be stored backwards
int counter=-1;
do{
counter++;
if(num%2)
answer[counter]=1;
else
answer[counter]=0;
num/=2;
}while(num);
//display the number
for(counter;counter>=0;counter--)
cout << answer[counter];
Just another suggestion of one way that will work. The previous example will work too, but you said you wanted a loop, not a recursive function. With this code, you also get the proper syntax for a do while loop:
PHP Code:
do
{
//code
...
}while(condition is true);
Depending on what you want to use the binary data for, you may want to save the binary data in a different format, rather than in an array.
Last edited by SolarFlare; October 6th, 2002 at 06:31 PM.
SolarFlare
Those who cling to life die and those who defy death live. -Sun Tzu
cout << endl;
return 0;
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|