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'
how should i ammend this? Please advise. Thanks.

you need ; after b++

Thanks! But it doesn't seem to get any output? Please advise.
Anything i should input to show output like f(5) = 5?
Thanks.

Thanks! But it doesn't seem to get any output? Please advise.
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;
}

please advise me whether it's correct?

>>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;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.