Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Code for counting no. of 0s and 1s in binary representation of a letter

Basically, I have to write a code such that:

  1. a letter is taken as an input.
  2. no. of 0s and 1s in the binary representation of it’s ascii value are counted
  3. 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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading