title: Count total set-bits from 1 to n
body: <p>I tried to solve this using loops. Can anyone tell me where I went wrong and what will be the output of it? I have tried using count set-bits concept for a given number.</p>
  <pre><code>#include &lt;bits/stdc++.h&gt;
  using namespace std;
  
  int main()
  {
      int res=0;
      int n;
      cout&lt;&lt;&quot;Enter the value of n&quot;;
      cin&gt;&gt;n;
      for(int i=1;i&lt;=n;i++)
      {
          while(i&gt;0)
          {
              if((i &amp; 1)==1)//checks whether the last bit is 1
              {
                 res++; //res will count the set bits
              }
              i=i&gt;&gt;1;
          }
  
      }
      cout&lt;&lt;res;
  }
  </code></pre>