I have been learning to program in C and decided that I would like to try making a denary to binary converter as this also included the use of inputs from the keyboard.
After creating a code that was manual (had to enter the results for every denary number into the code, e.g. for 1 write 1, for 2 write 10, for 3 write 11, etc.) I decided to look at codes that could take any denary number and turn it into the binary equivalent.
I found the following code (well, it was more complicated but I have stripped it down to what I wanted it to do and learnt lots in the process doing so) which I know works, however I do not really understand quite what is going on.
I understand what the main() function is doing, however I do not understand what the denary_binary function is doing. If anyone could explain what this means I would be extremely grateful. If you are also able to clear up which parts are user-defined (e.g. is 'rem' a particular function or could it have been called anything?), that would be awesome too.
Code:
#include <stdio.h>
#include <math.h>
int main()
{
int n;
int denary_binary(int n);
printf("\nEnter a denary number.\n");
scanf("%d", &n);
printf("\n%d = %d in binary.\n\n", n, denary_binary(n));
return 0;
}
int denary_binary(int n)
{
int rem, i=1, binary=0;
while (n!=0)
{
rem=n%2;
n/=2;
binary+=rem*i;
i*=10;
}
return binary;
}