k&r : finished chapter 2

master
Tibor Bizjak 2023-06-22 14:23:47 +02:00
parent e001baa96f
commit abccef71d3
2 changed files with 51 additions and 0 deletions

View File

@ -0,0 +1,35 @@
#include <stdio.h>
#include <stdlib.h>
#include "02-bitwise.h"
int bitcount(unsigned x);
/* parse command line args for bitcount, print result */
int main(int argc, char *argv[])
{
if (argc < 2) {
printf("error : expected argument x\n");
return 1;
}
unsigned x;
if (!int_of_string(&x, argv[1]))
return 2;
printf("%d\n", bitcount(x));
return 0;
}
/* x &= x-1 deletes the right most 1 bit
* suppose x = y10..0
* then x-1 = y01..1
* then x & x-1 = y00..0
* QED */
/* bitcount: count number of set bits in x, using the abova property */
int bitcount(unsigned x)
{
int b;
for (b = 0; x; b++)
x &= x-1;
return b;
}

View File

@ -0,0 +1,16 @@
#include <stdio.h>
char lower(char c);
int main()
{
int c;
while ((c = getchar()) != EOF)
putchar(lower(c));
return 0;
}
char lower(char c)
{
return (c >= 'A' && c <= 'Z') ? c + 'a' - 'A' : c;
}