### convert base 10 to binary program

closed account (EAXiz8AR)
Our assignment tells us to convert a base 10 number between 0 and 127 to binary BUT the catch is that we can't use any loops -_-

which I feel like makes the code very inefficient. I have the following below:

 ``123456789101112131415161718192021222324252627282930313233343536373839`` `````` int integer; cout << "Input a positive int between 0 and 127 inclusive: "; cin >> integer; cout << "Decimal " << integer << " converted to base 2 is: "; if (integer == 0) cout << "0"; else { if (integer <= 3) { cout << integer % 2; integer = integer / 2; cout << integer % 2; integer = integer / 2; } if (integer <= 7 && integer => 4) { cout << integer % 2; integer = integer / 2; cout << integer % 2; integer = integer / 2; cout << integer % 2; integer = integer / 2; } if (integer <= 15 && integer => 8) { cout << integer % 2; integer = integer / 2; cout << integer % 2; integer = integer / 2; cout << integer % 2; integer = integer / 2; cout << integer % 2; integer = integer / 2; }``````

but I feel like it is very inefficient. The nested if statements were to account for the number of digits that are in each binary number between X integer and Y integer. I feel like im too repetitive.

Can you guys point me to a solution where it is less repetitive, but without loops?

Thanks
Use a recursive function.
 ``1234567891011121314151617`` ``````#include #include using namespace std; void breakItDown(int a,string &ans){ //------------------------------- // Put something in here and call // breakItDown in this function. // Maybe save the answer in ans } int main(void){ string answer; int i(10); breakItDown(i,answer); cout << answer << endl; return 0; }``````

Topic archived. No new replies allowed.