+ 1
Binary equivalent
Can anyone tell how the code works in converting decimal no. to binary void Binary(int n) {if(n>1) (n/2); cout<<n%2; }
5 ответов
+ 1
~ swim ~
Ok. I thought he using while loop.
For recursion no need but by loop I mentioned. Because of just said binary process without considering code as it is incomplete...
OK. I edit as an alternative way.. Thank you..
+ 1
TY GUYS...my tutor said that the reminders are stored on stack...and it was a little bit difficult to understand...but the way swim told make sense...TY
0
[ Edit:
if you know binary convertion, and looking for recursive explanation only, then see @swim explanation.. ]
For ex: 8
8%2=0, 8/2=4
4%2=0, 4/2=2
2%2=0, 2/2=1
1%2=1, 1/2=0 stops,
So 01000, Take reminders in reverse...
1000 is 8's binary representation..
Your code has some flaws..
It should store reminders and print in reverse..
Edit:
Without recursion, code may look like...
void Binary(int n)
{
int a[20], i=0;
while(n>0){
a[i++]=n%2;
n=n/2;
}
for(int j=i-1; j>=0 ; j--)
cout<<a[j];