title: Recursion Binary to Decimal
body: <p>I am using C++ to write a program that uses recursion to convert a user input binary number to a decimal. I've played with this code for hours</p>
  
  <p>(earlier I initialized <code>i</code> with <code>i = binary.length();</code>)</p>
  
  <pre><code>    void bin2dec(string binary, int i)
  {
      double decNum=0;
  
      if (i &gt;= 0)
      {
          if (binary[i] = 0)
          {
              decNum = (decNum + 0);
          }
          else
          {
              decNum = (decNum + pow(2, (i-1)));
          }
          bin2dec(binary, i-1);
      }
      cout &lt;&lt; decNum;
  }
  </code></pre>
  
  <p>That is my recursion function. Unfortunately, I am stuck. The program runs but gives me incorrect values. For example, when I plug in 1 as the binary, I expect to get 1 decimal in return. But I get .5 number. Is my calculation wrong or am I using recursion incorrectly?</p>
  
  <p>Upon receiving suggestions, I made the following changes. However, the program still returns an incorrect value.</p>
  
  <pre><code>void bin2dec(string binary, int i)
  {
      double decNum=0;
      if (i &gt;= 0)
      {
          if (binary[i] == 1)
          {
              decNum = (decNum + pow(2, i));
          }
          else if (binary[i] == 0)
          {
              decNum = (decNum + 0);
          }
          bin2dec(binary, i - 1);
          cout &lt;&lt; decNum;
      }
  }
  </code></pre>