I've been doing some homework on basically just converting an inputted integer into it's binary form. So far I've made great progress on converting the inputted integer into a binary number as well as declining any number that is negative.
The problem I'm having however is counting the number of 1's within the binary code and printing how many one's are in the binary representation. I've tried many examples of code from the internet and my book(Not direct copy and paste, I've tried fitting it to my needs) but so far have come to no avail. I believe it's cause I'm not focusing on a specific number.
Basically, I'm new to C, very new. I've done most of my past 2 semesters in Java and have NO programming experience in any other language, just looking for a helping hand. Just to re-iterate the question:
How can I count the number of one's in an inputted binary representation?
Example: Inputted 44, binary is 101100 Number of 1's: 3
EDIT: So far with the implemented code my new problem now is that whatever integer I input, the output remains 12.
#include <stdio.h>
int main(void)
{
int integer; // number to be entered by user
int i, b, v;
unsigned n = 0;
while(v) {
++n;
v &= v - 1;
}
printf("Please type in a decimal integer\n"); // prompt
fflush(stdout);
scanf("%d", &integer); // read an integer
if(integer < 0)
{
printf("Input value is negative!"); // if integer is less than
fflush(stdout);
return; // zero, print statement
}
else{
printf("Binary Representation:\n", integer);
fflush(stdout);}
for(i = 31; i >= 0; --i) //code to convert inputted integer to binary form
{
b = integer >> i;
if(b&1){
printf("1");
fflush(stdout);
}
else{
printf("0");
fflush(stdout);
}
}
printf("\n");
fflush(stdout);
printf("Number of 1's in Binary Representation:%d\n", n);
fflush(stdout);
printf("\n");
fflush(stdout);
return 0;
}//end function main