[courses] [C] lesson 10 exercise 1 ans (sorry for the # of posts)

Morgon Kanter admin at surgo.net
Tue Nov 12 19:46:57 EST 2002


Here it is. I am still wondering what, exactly, that cycling through the bits 
thing that was included in the lesson code, but I suppose I'll look at it 
again after dinner. Surprisingly, this was easier than the second, but I had 
experience this time.

#include <stdio.h>

#define BITS 32

int main() {
   char line[10];
   unsigned short int i, count = 0;
   int input;

   printf("Enter an integer: ");
   fgets(line, sizeof(line), stdin);
   sscanf(line, "%i", &input);

   for(i = 0; i < BITS; i++) {
      if( ((input & (1 << i)) >> i)) count++;
/* that was the part I don't understand */
   }

   printf("There were %u set bits\n", count);
}



More information about the Courses mailing list