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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
   
   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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>
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.