From abccef71d3f407b15b932523234710e4cafa1c5d Mon Sep 17 00:00:00 2001 From: Tibor Bizjak Date: Thu, 22 Jun 2023 14:23:47 +0200 Subject: [PATCH] k&r : finished chapter 2 --- k&r/02-types-operators-and-exp/02-09.c | 35 ++++++++++++++++++++++++++ k&r/02-types-operators-and-exp/02-10.c | 16 ++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 k&r/02-types-operators-and-exp/02-09.c create mode 100644 k&r/02-types-operators-and-exp/02-10.c diff --git a/k&r/02-types-operators-and-exp/02-09.c b/k&r/02-types-operators-and-exp/02-09.c new file mode 100644 index 0000000..d91732c --- /dev/null +++ b/k&r/02-types-operators-and-exp/02-09.c @@ -0,0 +1,35 @@ +#include +#include +#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; +} diff --git a/k&r/02-types-operators-and-exp/02-10.c b/k&r/02-types-operators-and-exp/02-10.c new file mode 100644 index 0000000..acf6bfe --- /dev/null +++ b/k&r/02-types-operators-and-exp/02-10.c @@ -0,0 +1,16 @@ +#include + +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; +}