I am having difficulty in understanding a line in a decimal to binary conversion program

37 Views Asked by At

Alright, I know this is a silly question to ask as it is related to reverse for loop but I am struggling to understand this. I even tried to make a separate reverse for loop program to clear the context but I am still in trouble.

So here is my code

#include<iostream>
using namespace std;
int main()
{
    int i,d,j=0,b[100];
    cin>>d;
    while(d>0)
    {
        b[j]=d%2;
        d=d/2;
        j++;
    }
    //cout<<j;
    for(i=j-1;i>=0;i--)
    {
        cout<<b[i];
    }
}

Now, please explain me the for-loop. Why it should be i=j-1;i>=0;i--? Can't it be i=j;i>0;i--?

When I am giving 109 as input and using i=j;i>0;i-- I am receiving 6946348110110 as output and if I am using i=j;i>=0;i-- then I am receiving 69463481101101

I am a novice. Please help!

1

There are 1 best solutions below

0
On

The last time the 'while' loop is executed, b[j]=d%2 will add a value at, let's say, the position 4 (b[0,1,2,3,4]). The variable 'j' will still be increased by one to end the loop, taking the value 5. So, when starting your 'for' loop, you'll got a tab going to 4, but a 'j' value of 5, explaining the utility of using i=j-1. Your loop will now check the values [4,3,2,1,0] instead of [5,4,3,2,1], which is not exact.