-2

I am a beginner in programming and I am trying to understand a code that converts decimal to binary. The code is as follows:

#include <stdio.h>

int main()
{
  long int DN,quo;
  int rem[106],i=1,j;

  printf("give me a decimal number: ");
  scanf("%ld", &DN);

  quo = DN;

  while(quo!=0)
  {
     rem[i]= quo % 2;
     quo = quo / 2;
     i++;
  }

  printf("Equivalent binary value of your decimal number %ld\n: ",DN);

  for(j = i-1 ;j> 0;j--)
     printf("%d",rem[j]);
}

Can anyone help me understand the part beginning with the while loop? I am very sorry for posting such a simple question.

Michael Albers
  • 3,721
  • 3
  • 21
  • 32
Exotic Cut 5276
  • 235
  • 4
  • 18
  • So how is the for loop at the bottom making sure that I get my remainders in reverse order? – Exotic Cut 5276 Feb 02 '17 at 04:12
  • Its a code to convert decimal number to binary. further reading http://math.stackexchange.com/questions/86207/converting-decimalbase-10-numbers-to-binary-by-repeatedly-dividing-by-2 and http://stackoverflow.com/questions/2548282/decimal-to-binary-and-vice-versa – roottraveller Feb 02 '17 at 04:20
  • 1
    Please use a debug executable and with the help of any debugger like gdb you can very well understand yourself what values are getting stored in `rem[]` and what is the value of `i` just before the `for` loop. It will improve your understanding of the code. – Rishi Feb 02 '17 at 05:13
  • @yellowantphil that is what I am confused about. I can acknowledge the fact that I am not so logically driven. So the initialization value is j = i -1, since I start with i = 1 in my code above, and let's say I want to find the binary conversion of 8, my rem [1] = 0, rem [2] = 0, rem [3] = 0 and rem [4] = 1. Now coming to the for loop, since I start with j = i - 1 and then decrease until j > 0, does it mean I take i = 3 first? I hope I do not sound too confusing here. – Exotic Cut 5276 Feb 02 '17 at 06:33

2 Answers2

2

Suppose input decimal number is 13

Step 1. 13/2 , Remainder = 1, Quotient = 6
Step 2. 6/2 , Remainder = 0, Quotient = 3
Step 3. 3/2 , Remainder = 1, Quotient = 1
Step 4. 1/2 , Remainder = 1, Quotient = 0

Now, the Binary equivalent of 13 is the remainders in reverse order : 1101

msc
  • 33,420
  • 29
  • 119
  • 214
0

This is an implementation of the standard way to convert a number to its decimal representation.

  1. [quotioent, remainder] = a ÷ 2
  2. d[i] = remainder
  3. If quotient is 0 we're done
  4. else goto 1
  5. Read d[i] backwards and print it out.
awiebe
  • 3,758
  • 4
  • 22
  • 33