CS2263/Labs/Lab1/countOnes.c

33 lines
711 B
C
Raw Permalink Normal View History

2023-05-22 23:28:51 -03:00
#include <stdio.h>
int main(){
int value;
int iErr;
printf("Value to examine: ");
iErr = scanf("%d",&value);
if(iErr != 1){
printf("Unable to read the value\n");
return 0;
}
if(value <= 0) {
printf("Value must be positive\n");
return 0;
}
int binaryArray[32];
int arrayLength = 0;
while(value > 0) {
binaryArray[arrayLength] = value % 2;
value = value/2;
arrayLength++;
}
int counter = 0;
for(int i = arrayLength; i > 0; i--) {
if (binaryArray[i] == 1) {
counter++;
}
}
printf("Number of ones: %d", counter);
return 0;
}