Issue
So I am an absolute beginner in C and I have to make a decimal to hexadecimal converter.
So I guess I would need to make a loop that loops until the result is 0.
But how do I make it remember all the remainders? The number is going to be input with scanf so I can't tailor the code to it.
Now I would want to do something like this
while(number(n)!=0)
{
number0 / 16 = number1
number0 % 16 = remainder0
number1 / 16 = number2
number1 % 16 = remainder1
.....
number(n-1) / 16 = 0
number(n-1) % 16 = lastremainder
}
hex = lastremainder, ..., remainder2, remainder1, remainder0
But how can I make the program create variables during the loop? Do I have to use a complete different method? I took a look at other decimal to hex converters and I don't quite get how they work.
Like I said I am an absolute beginner so sorry if the question is stupid.
Thank you for the replies. So arrays are the answer to my problem? I don't fully understand them right now but thank you for the point in the right direction.
Solution
Make an array and write the remains in it:
int array[50];
int counter=0;
[...]
while(number!=0)
{
[...]
array[counter]=number%16;
number/=16;
++counter;
}
The line array[counter]=number%16;
means that the first element in the array will be number%16 - the second will be (number/16)%16 etc.
You need the counter
to know how many elements there is in the array (how much remains), so that you can later write them backwards.
(Take into consideration here that you have a limit - int array[50];
because, what happens if your number is really big and you have more than 50 remains? The solution would be to write this dynamically, but I don't think you should worry about that at this point.)
Answered By - Eutherpy Answer Checked By - David Marino (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.