Basically, I have to write a code such that:
- a letter is taken as an input.
- no. of 0s and 1s in the binary representation of it’s ascii value are counted
- report (no. of 0s)*(no. of 1s)
Please help me find mistakes in my code.
#include <stdio.h>
int main(){
int x,y,count0,count1,a,r;
scanf("%c",&x);
a = (int)x;
count0 = 0;
count1 = 0;
while(a != 0){
r=a%2;
if(r == 0)
count0 = count0 + 1;
else if(r == 1)
count1 = count1 + 1;
a = a/2;
}
y = count1 * count0;
printf("%d\n",count0);
printf("%d\n",count1);
printf("%d",y);
return 0;
}
Clearly this is wrong as for the input ‘A’, it should print 5,2,10 but it is giving out 16,7,112.
>Solution :
Because you declared x as int, scanf("%c",&x); produces:
test.c:5:17: warning: format ‘%c’ expects argument of type ‘char *’, but argument 2 has type ‘int *’ [-Wformat=]
Also default char is signed, which may produce surprising numbers of ones and zeroes if you encounter one of the negative values.
Change the type of x to be unsigned char:
unsigned char x;
int y,count0,count1,a,r;
then the code should do what you wanted.
If you don’t have warnings enabled in your compiler, enable them now. They are usually helpful in detecting problems like this.