Convert decimal number into binary using recursion in C - c

I had this code. Everything is fine with the code. The only thing is I am not getting why we are multiplying by 10 in last second line when the function convert() is being called recursively.
#include<stdio.h>
int convert(int);
int main()
{
int dec,bin;
printf("\n Enter the decimal no.:");
scanf("%d",&dec);
bin=convert(dec);
printf("\n The binary equivalent is %d",bin);
return 0;
}
int convert(int dec)
{
if(dec==0)
return 0;
else
return ((dec%2)+10 * convert(dec/2));
}
Someone help me. Thanks in advance.

You seem not to understand what is happening:
Imagine you are converting the number 9 into binary digits, then you should get "1001", which you are (using your program).
However, the "1001" (one zero zero one) is shown as 1001 (one thousand and one).
Oh, maybe you don't understand that multiplying by ten and adding something is the way to append something at the end: if I ask to you append the digit 2 to the digit 3, you will do the following:
3 * 10 + 2 = 32
You are doing the same thing here (but the digits "pretend" to be binary digits).

Related

Can someone explain me the working of the code? This code is supposed to print the reverse of a number

// C program to print reverse of a number using for loop
#include<stdio.h>
int main()
{
long int num,i;
int d;
printf("\n enter number");
scanf("%ld",&num);
printf("\n the reverse of number %ld is ",num);
for(i=0;num>0;i++)
{
d=num%10;
num=num/10;
printf("%d",d);
}
return 0;
}
I think there is no terminating given in this code as the for loop will run infinte times, but this code is working fine, so can someone explain this code?
In order to understand the loop you need to understand the working of % 10 and /= 10 operations.
The first one, the remainder of division by ten, chops off the last decimal digit. The second one drops that digit from the number, because the division is done in integers.
Dividing a number by ten repeatedly will make it a zero aftre a number of iterations equal to the number of digits in the number, so that is when your loop is going to stop.

Decimal precision using integer

I am programming a uC in C language and I need to show a float number with 4 precision digits. The thing here is that my number is not really a float type. I have the integer part and the decimal part of the number in two different integer variables. Let say: int digit and int decimal.
I tried using printf ("%d.%d"); That works fine when my decimal number is 6524, but the problem comes when it is exactly 65 since it doesnt show 4 decimals.
I tried using printf ("%d.%04d"); but when my decimal part is exactly 65 it shows 0065 which is not mathematically correct (I would need 6500)
I looked for any argument of printf which completes with zeros at the end but could not find anything. All of them complete with leading zeros which is not useful for me in this case.
I also though about checking if my number is minor that 10, 100 or 1000 and multiply it by 1000, 100 or 10 respectively. But it will not work when the decimal part is exactly 0, since 0*1000 will still be 0 and not 0000.
Any idea on how to solve this? Please let me know if I am not completely clear and I will provide more information
Thanks!
Since printf returns the number of characters printed, you can do it, somewhat clumsily, as follows:
printf("%d.", int_part);
int digits = printf("%d", frac_part);
while (digits++ < 4) putchar('0');
I have to say, though, that it is a very eccentric form of representing a floating point number, and you might seriously want to rethink it.
Another wired possibility is to convert the decimal part to a string and then fill it with 0:
int main() {
int i, d, len;
char p[10];
i = 189;
d = 51;
// convert the number to string and count the digits
snprintf(p, 10, "%d", d);
len = strlen(p);
while (len < 4) {p[len] = '0'; len++;}
p[len] = '\0';
fprintf(stdout, "%d.%s\n", i, p);
// you can also go back to int
d = atoi(p);
fprintf(stdout, "%d.%d\n", i, d);
}
Combine both your answers: multiply by 10, 100 or 1000 as necessary, but still print with %04d.

C program to print sum of squares of digits of a given number?

I want to write a c program that prints the sum of the squares of a given number.
For example, if the given number is 456, the output would be 4^2+5^2+6^2=16+25+36=77.
So i have written this code and i want to know why it doesn't work if the user gives a number like 100,101,102 or 200,300 etc. It works fine for other numbers. I guess it has something to do with the dowhile loop. Please help me.
#include<stdio.h>
#include<conio.h>
#include<math.h>
main()
{
int n,t=0,r,q;
printf("Enter the number to be tested: ");
scanf("%d",&n);
q=n;
do
{
r=q%10;
t=t+pow(r,2);
q=q/10;
}
while(q%10!=0);
printf("%d",t);
getch();
}
Your stopping condition is wrong: q%10!=0 will become "true" as soon as you reach the first zero in a decimal representation. For example, for a number 6540321 your program would add 32+22+12, and stop, because the next digit happens to be zero. Squares of 6, 5, and 4 would never be added.
Use q != 0 condition instead to fix this problem. In addition, consider replacing
t=t+pow(r,2);
with a more concise and C-like
t += r*r;
Change
while(q%10!=0);
To
while(q);
Which is the short for
while(q!=0);
This is done to prevent to loop from ending once the value of q is a multiple of 10.

Binomial coefficient in C

Here you can find the problem I'm trying to solve:
For integers n and k (0<=k<=n<1001) determine (binomial coefficient).
Input
The first line of the standard input contains one integer t (t<1001) which is the number of test cases.
In each of the next t lines there are numbers n and k.
Output
For each test print (binomial coefficient).
Example:
Input
3
0 0
7 3
1000 2
Output:
1
35
499500
I can't seem to find anything wrong in my solution (other than it's written very poorly - I've started programming quite recently):
#include <stdio.h>
int main()
{
unsigned long int t,n,k,binomial=1;
unsigned long int number=1;
for(scanf("%lu",&t);t>0;t--)
{
scanf("%lu%lu",&n,&k);
if(k<(n/2)) k=n-k;
for(binomial=1,number=1;n>k;k++)
{
binomial=binomial*(k+1)/number;
number++;
}
printf("%lu\n",binomial);
}
return 0;
}
It works fine for the example input, but the solution is judged via a problem site
(http://www.spoj.pl/SHORTEN/problems/BINOMIAL/english/)
and the solution is not accepted. I tried other inputs too and all of them gave back the right output. My question is: Is there a reason why this solution is invalid?
As 1000C500 is around 300 digits, it cant be stored in an unsigned long. In short, you need to start over and think of a better technique.

Trying to reverse the order of the digits in an integer, extra digits are shown

Firstly, this is a homework assignment, and I am very new to programming in C. What I am trying to accomplish is the user puts in an integer, and then each individual digit of that integer is printed on a new line, like below:
Enter integer: 1234
The digits are:
1
2
3
4
My problem is that whatever integer you input, for some reason a 7 and a 4 are added on to the end. Below is my code and an example of the problem:
#include <stdio.h>
#define Success 0
int main()
{ int integer;
int reverse;
int digit;
printf("Enter Integer: ");
scanf("%d", &integer);
/* Reverse the numbers in the integer */
while (integer != 0) {
digit = integer%10;
reverse = (reverse * 10) + digit;
integer = integer / 10;
}
/* Print the numbers of the reverse integer, in reverse order */
while (reverse != 0) {
digit = reverse%10;
printf("%d\n", digit);
reverse = reverse / 10;
}
return Success;
}
Example of problem:
Enter Integer: 12345
1
2
3
4
5
7
4
Anyone have any ideas as to what might cause this outcome? By printing reverse I have narrowed it down to a problem with the first while loop.
Reverse is not initialized. This means there could be any value in that variable when you start touching it. Set it to 0 after you declare it and see what happens.
One issue is that reverse needs to be initialized:
reverse = 0;
Hint: are the values of digit and reverse always what you expect they should be? Try printing them out every iteration, so you can see. Or, even better, learn to use your platform's debugger and just step through it.
Spoiler: you'll probably get more out of solving it yourself, with the hint above.
But ... you didn't initialize reverse to zero before starting. That would be a good idea.
Check the initial value of reverse (hint: there isn't one). Right now it's starting with garbage in it.
I would actually print the int to a string and reverse that through iterating through the string in reverse order. See sprintf for details.
I would scan the integer into a string, use the strlen function to determine its length, and then traverse it backwards.

Resources