I have got this question: Write function of f(x) that return the number of bits set to 1 in an unsigned integer.
So the outcome of the result will be sometime like f(5) = 2 cos [5 in binary is 101 and it got 2 '1s')

Here's my program:
#include <stdio.h>
int bitcount(unsigned x);
main()
{
int b;
int x;
for (b=0; x!=0; x >>=1)
if (x &01)
b++
return b;
}

And the error is "return b" >> parse error before `return'

3
Contributors
7
Replies
8
Views
11 Years
Discussion Span
Last Post by Ancient Dragon

you need ; after b++

Anything i should input to show output like f(5) = 5?
Thanks.

Anything i should input to show output like f(5) = 5?
Thanks.

what output are you expecting? your program does not contain any code to print anything on the screen. For C programs use printf() function, c++ programs use cout class. See your text book for instructions about how to use these functions.

Hi,

Is it something like this?

#include <stdio.h>
int bitcount(unsigned x);
int main(void)
{
printf("%d",bitcount((unsigned));
return 0;
}

int bitcount(unsigned x)
{
int b;
int x;
for (b=0; x!=0; x >>=1)
if (x &01)
b++
return b;
}

>>Is it something like this?

I don't know. You have not said what you want it to look like yet. You should compile and run your program to see for yourself whether it is right or not.

it will prompt something like ask me to enter for x.
and when i enter 3, it will check for the number of 1s in binary format of 3 (011).
so i will expect an output of f(3) = 2 to be shown.
seem like my program doesn't work again....could u plz advise which part i should add ??

The problem is that your program has several compiler errors and is badly formatted. Here is a correction

``````#include <stdio.h>
int bitcount(unsigned x);
int main(void)
{
printf("%d\n",bitcount(3));
return 0;
}

int bitcount(unsigned x)
{
int b;
for (b=0; x!=0; x >>=1)
{
if (x &01)
{
b++;
}
}
return b;
}``````
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.